0

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();
GibboK
  • 68,054
  • 134
  • 405
  • 638

3 Answers3

1

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

Ahmed Magdy
  • 5,576
  • 8
  • 40
  • 74
0

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.

Nagg
  • 6,080
  • 3
  • 34
  • 40
  • are you able to give me an example of dynamic LINQ query for my case? – GibboK Jul 19 '11 at 08:22
  • take a look to http://www.singingeels.com/Blogs/Nullable/2008/03/26/Dynamic_LINQ_OrderBy_using_String_Names.aspx – Nagg Jul 19 '11 at 08:25
0

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

Community
  • 1
  • 1
Björn Lindqvist
  • 17,917
  • 18
  • 78
  • 117