I have Post
and PostImage
entities. A Post
entity can have a list of PostImage
entities (i.e., one-to-many). I want to fetch a list of all posts and include all of its list of images. So I wrote the following piece of code:
var posts = _appDataContext.Posts
.Select(x => new
{
x.Id,
x.Title,
x.Body,
Images = x.Images.Select(y => new
{
y.Id
})
});
The code is all executed in the database which is what I want, but here's the catch. From the console log, it appears that EF is first fetching the list of posts, and then it loops over them to fetch their corresponding images (extra queries + extra fetching time). Is there any other way to fetch the data all at once (posts + their images). Both posts and images have extra columns, that's why I used the Select
statement; to filter out the columns that I don't need. I tried using Include
, but nothing has changed.
P.S. I'm using EntityFramework Core.