9

I am implementing a forum where each post can have comments.

I want to load a batch of N posts so each post loads the first K comments.

I've got this code to start with, but it currently includes all the comments with each post. How do I only load first K comments with each post without having to make K calls to the database?

List<ForumPost> result = ctx
                            .ForumPosts
                            .Include("Comments") // <-- ??? How to take first K ???
                            .Where(i => i.Thread.ID == threadID)
                            .OrderByDescending(i => i.Date)
                            .Take(N).ToList();

Thanks!

0

2 Answers 2

9

(Currently, in EF you cannot filter or limit the Included related entities in any way). It's possible in EF Core since 5.0: Filtered include.

If you need to avoid the multiple queries, there are solutions, but they all involve working directly on the SQL side. You can use: TVF (table valued functions), stored procedures, views, or a simple query. In each case there are different solutions to map the results to your entities. And the mapped entities will be non-trackable, so that you cannot modify and write them back to the server (unless you add them explicitly to an existing DbContext)

You can read this article by Julie Lerman to see what I'm speaking about: Use Projections and a Repository to Fake a Filtered Eager Load.

You can vote for a related feature at Data User's voice. Look for "Allow filtering for Include extension method". Most probably, if this is implemented, it will also be possible to use .Take in this situation.

For more information on the evolution of this feature, take a look at EF Core github issue 1833: Support filtered Include. There you can find interesting things like:

3
  • Yes thanks, I voted for that one.
    – Paceman
    Sep 19, 2015 at 4:50
  • @Paceman looks like the solution from the link works for your case (which I believe involves one-to-many relationship). What I tested involves many-to-many relationship and it did not work.
    – Hopeless
    Sep 19, 2015 at 12:43
  • Anything new in EF Core? Mar 7, 2018 at 10:14
3

I think Include currently does not have that filter feature. You can try using explicit loading instead. However with this way the query does not look nice, I would use a foreach after you have a List of ForumPost:

List<ForumPost> result = ctx
                        .ForumPosts                            
                        .Where(i => i.Thread.ID == threadID)
                        .OrderByDescending(i => i.Date)
                        .Take(N).ToList();
//start loading top K comments from each post
foreach(var post in result){
    ctx.Entry<ForumPost>(post).Collection("Comments")
                              .Query()
                              .Take(k);//assume k is a constant
}

Edit: (to make it work with one round trip to db)

The duplicate question has an answer about this but it's not working if the relationship is many-to-many, at least that's from what I tested in EF6. For many-to-many relationships, I tried finding a solution and ended up with the following code which works BUT there may be some trade-off on client side where you need a loop to reset all RelationshipEntries' State to Unchanged to mimic that they all are loaded from database.

ctx.Configuration.LazyLoadingEnabled = false;
var stateManager = ((IObjectContextAdapter)ctx).ObjectContext.ObjectStateManager;
var result = ctx.ForumPosts.Where(i => i.Thread.ID == threadID)
                .Select(e => new { e, Comments = e.Comments.Take(k) })
                .AsEnumerable()
                .Select(e => {
                   //set the Comments manually
                   e.e.Comments = e.Comments;
                   //Reset RelationshipEntries' state
                   foreach(var c in e.Comments) {
                      stateManager.ChangeRelationshipState(e.e, c, o => o.Comments, 
                                                           EntityState.Unchanged);
                   }
                   return e.e;
                }).ToList();

The loaded result is even cached into Local. Now it does just one round trip to db (right after calling AsEnumerable()).

2
  • This is one way but it still uses multiple DB calls doesn't it? I was hoping that there was a way to avoid N calls to the database by using some linq syntax that would use witchcraft to translate it into a single SQL statement.
    – Paceman
    Sep 18, 2015 at 7:36
  • 1
    @Paceman yes, you're right, it requires multiple round trips to db. But as I said there is currently no way to use Include as what you want. I'm however not so sure about that, let's see if some others could give some suggestion.
    – Hopeless
    Sep 18, 2015 at 7:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.