Reputation: 73908
Hi I use Linq and EF 4.
I have this query, but it seems not able to order the result by a string variable sortExpression
.
I suppose I'm doing smt wrong in "it."
part.
Notes: sortExpression
could have like Title
Could you please have a look and tell me what is wrong in my syntax? Thanks for your help
var myContentsForAuthor = from c in context.CmsContents
join a in context.CmsAuthors on c.AuthorId equals a.AuthorId
join u in context.aspnet_Users on a.UserId equals u.UserId
orderby("it." + sortExpression)
where u.UserId == myUserGuid && c.IsDeleted == false && c.Title.Contains(nameSearchString)
select c;
return myContentsForAuthor.ToList();
Upvotes: 0
Views: 106
Reputation: 6030
You can acheive what you want like the following:
var myContentsForAuthor = from c in context.CmsContents
join a in context.CmsAuthors on c.AuthorId equals a.AuthorId
join u in context.aspnet_Users on a.UserId equals u.UserId
where u.UserId == myUserGuid && c.IsDeleted == false && c.Title.Contains(nameSearchString)
select c;
if(sortExpression == 'Title')
{
return myContentsForAuthor.Where(c => c.Title).ToList();
}
if(sortExpression == 'Author')
{
return myContentsForAuthor.Where(c => c.Author.Name).ToList();
}
NOTE: Always put orderby
at the end of your queries.
EDIT: I updated the code EDIT2: updated it to be more simpler
Upvotes: 1
Reputation: 20354
You need to construct a dynamic linq query. See the answers to this question How can I do an OrderBy with a dynamic string parameter?.
Upvotes: 0
Reputation: 6142
orderby
requires to specify member. in your case - orderby c(?).Titile
and not ordeby(string)
. It seems that you have to use expression trees (dynamic LINQ) to create needed query.
Upvotes: 0