How to create view model without sorting collections in memory.

Posted by Chevex on Stack Overflow See other posts from Stack Overflow or by Chevex
Published on 2011-01-13T22:04:24Z Indexed on 2011/01/14 19:53 UTC
Read the original article Hit count: 248

I have a view model (below).

public class TopicsViewModel
{
    public Topic Topic { get; set; }
    public Reply LastReply { get; set; }
}

I want to populate an IQueryable<TopicsViewModel> with values from my IQueryable<Topic> collection and IQueryable<Reply> collection. I do not want to use the attached entity collection (i.e. Topic.Replies) because I only want the last reply for that topic and doing Topic.Replies.Last() loads the entire entity collection in memory and then grabs the last one in the list. I am trying to stay in IQueryable so that the query is executed in the database.

I also don't want to foreach through topics and query replyRepository.Replies because looping through IQueryable<Topic> will start the lazy loading. I'd prefer to build one expression and have all the leg work done in the lower layers.

I have the following:

IQueryable<TopicsViewModel> topicsViewModel = from x in topicRepository.Topics
                                              from y in replyRepository.Replies
                                              where y.TopicID == x.TopicID
                                              orderby y.PostedDate ascending
                                              select new TopicsViewModel { Topic = x, LastReply = y };

But this isn't working. Any ideas how I can populate an IQueryable or IEnumerable of TopicsViewModel so that it queries the database and grabs topics and that topic's last reply? I am trying really hard to avoid grabbing all replies related to that topic. I only want to grab the last reply.

Thank you for any insight you have to offer.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ