ojek
ojek

Reputation: 10078

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();

Upvotes: 3

Views: 500

Answers (1)

user743382
user743382

Reputation:

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.

Upvotes: 2

Related Questions