开发者

Linq help with OrderBy

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. 开发者_Go百科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();


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


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.


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?.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜