I have something like this:
var thread = _forumsDb.Threads
.Include("Posts")
.Single(t => t.Id == threadId);
Now, when i have a single thread, and a collection of posts within it, i want to count those posts, and then take some amount of them and remove the rest.
var count = thread.Posts.Count();
var tmp = thread.Posts.Skip(15).Take(15);
thread.Posts.Clear();
thread.Posts = tmp;
But that obviously doesn’t work. So, how can i add collection to a collection? Is the thread.Posts.Clear(); appropriate here, or could i do it better?
In order to load only the 15 posts from the database you need and to perform only a single database query I would use a projection:
Note that you need to order by some property if you want to use
TakeandSkipwith LINQ to Entities. If in doubt just order by the post’sId.If the relationship between
ThreadandPostsis one-to-many EF will populate thethread.Postscollection automatically with the 15 loaded posts.