Filter by inclusion in EF Core

I am trying to filter the initial request. I put leaflets from the model into it. I am trying to filter based on the property of one of the inclusions. For instance:

using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ToList(); } 

How can I also say .Where(w => w.post.Author == "me") ?

+19
source share
5 answers

Not feasible

The discussion on this topic continues: https://github.com/aspnet/EntityFramework/issues/1833.

I would suggest looking for any of the third-party libraries listed there, for example: https://github.com/jbogard/EntityFramework.Filters

+16
source

You can also cancel the search.

 { var blogs = context.Author .Include(author => author.posts) .ThenInclude(posts => posts.blogs) .Where(author => author == "me") .Select(author => author.posts.blogs) .ToList(); } 
+7
source

Not sure about Include () AND ThenInclude (), but it's easy to do with a single include:

 var filteredArticles = context.NewsArticles.Include(x => x.NewsArticleRevisions) .Where(article => article.NewsArticleRevisions .Any(revision => revision.Title.Contains(filter))); 

Hope this helps!

+1
source

Although this (still being discussed) is not possible with EF Core, I managed to do this with Linq to Entities on top of the EF Core DbSet. In your case, instead of:

 var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .ToList() 

.. you will have:

 await (from blog in this.DbContext.Blogs from bPost in blog.Posts from bpAuthor in bPost.Author where bpAuthor = "me" select blog) .ToListAsync(); 
+1
source

The simplest inline solution that I used would be something like:

 using (var context = new BloggingContext()) { var blogs = context.Blogs .Include(blog => blog.Posts) .ThenInclude(post => post.Author) .FromSql("Select b.* from Blogs b inner join Posts p on b.BlogId = p.BlogId where p.Author = 'me'") .ToList(); } 
0
source

Source: https://habr.com/ru/post/1267154/


All Articles