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
  • 71,848
  • 143
  • 435
  • 658

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,956
  • 8
  • 43
  • 75
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.

EgorBo
  • 6,120
  • 3
  • 35
  • 40
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
  • 19,221
  • 20
  • 87
  • 122