Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First + lazy loading, projection does not work as expected

I have something like this:

var tmp =_forumsDb.Threads
.Where(t => t.Id == variable)
.Select(t => new { Thread = t, Posts = t.Posts.Take(1) })
.Single();

Now, i expect tmp.Thread.Posts.Count(); to be 1, but it takes all posts that i have in database. Is it possible to use projection that takes explicit amount of posts, do it in a single query without turning off lazy loading?

Edit: I tried doing something like this, but it does not work either:

var tmp =_forumsDb.Threads
.Where(t => t.Id == variable)
.Select(t => new { Thread = t, Posts = t.Posts.OrderBy(p => p.DateCreated).Take(1) })
.Select(t => t.Thread)
.Single();
like image 603
ojek Avatar asked Feb 03 '26 01:02

ojek


1 Answers

tmp.Thread.Posts is the navigation property for which lazy loading is configured. Since it isn't yet loaded, accessing it loads all the remaining posts.

tmp.Posts is not a navigation property. That's the one you should be able to access without triggering another query.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!