none
OrderBy and Projection RRS feed

  • Question

  • Hello,

    I have the following Query:

    IList<PostModel> posts = context.Posts.Select(x =>
      new PostModel {
        Id = x.Id,
        Title = x.Title
    }).OrderBy(x => x.Id).ToList();
    


    I am using a projection with "new PostModel" so I avoid to load fields that contains binary data.

    By using a projection the query runs on the SQL Server instead of being loaded into memory.

    The problem is that I am not able to do "OrderBy(x => c.Created)" because PostModel does not have the "Created" property.

    Can I change the query to sort by "Created" date and keep the projection so it runs in the database?

    Thank You,

    Miguel
    Sunday, February 5, 2012 12:50 PM

Answers

  • Switch the .OrderBy() and the .Select() ;-)
    ----------------------------------
    http://jendaperl.blogspot.com
    A Perl developer in the world of C#
    Sunday, February 5, 2012 4:01 PM
  • Hi Miguel;

    As JendaPerl stated change the order of the methods Select and OrderBy and change the lambda expression in the OrderBy method as shown below.

     

    IList<PostModel> posts = context.Posts
                                    .OrderBy(x => c.Created)
                                    .Select(x => new PostModel 
                                    {
                                        Id = x.Id,
                                        Title = x.Title
                                    }).ToList();
    
    

     

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Sunday, February 5, 2012 7:16 PM

All replies

  • Switch the .OrderBy() and the .Select() ;-)
    ----------------------------------
    http://jendaperl.blogspot.com
    A Perl developer in the world of C#
    Sunday, February 5, 2012 4:01 PM
  • Hi Miguel;

    As JendaPerl stated change the order of the methods Select and OrderBy and change the lambda expression in the OrderBy method as shown below.

     

    IList<PostModel> posts = context.Posts
                                    .OrderBy(x => c.Created)
                                    .Select(x => new PostModel 
                                    {
                                        Id = x.Id,
                                        Title = x.Title
                                    }).ToList();
    
    

     

     


    Fernando (MCSD)

    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Sunday, February 5, 2012 7:16 PM