Home > Net >  Ef (core) 6 : Is Include needed just for filtering?
Ef (core) 6 : Is Include needed just for filtering?

Time:08-11

My question is so basic that I can't find topics that answer it; or if they do, they focus on the "hard part" of whatever question was asked, and never on the absolutely obvious aspect -- which I'm about to ask.

Here goes :

If I want to filter the Blogs on some property of Post (without including the Post in the result), then do I need an Include statement?

In other words :

Will this return all the Blogs that have a Post with an empty title...

var badBlogs = context.Blogs
   .Where(b => b.Posts.Any(p => p.Title == String.Empty));

...Or do I absolutely need this for the filtering to work as expected :

var badBlogs = context.Blogs
   .Include(b => b.Posts) // <-- this
   .Where(b => b.Posts.Any(p => p.Title == String.Empty));

Note: I'm using the traditional Blog/Post/Author structure of all EF examples

CodePudding user response:

Include/ThenInclude has a purpose only when loading related entities. It has no effect on filter or other LINQ operators.

Include works only when retrieved full object from database. It means that if you have Select, Include can be ignored:

var badBlogs = context.Blogs
   .Include(b => b.Posts) 
   .Select(b => new Blog { Id = b.Id, ... }); // Include ignored

But not in this case:

var badBlogs = context.Blogs
   .Include(b => b.Posts) 
   .Select(b => new { Blog = b }); // Include works

We still retrieve full object but projected to property.

  • Related