ef core 5.0如何过滤包括 [英] ef core 5.0 How to Filtered Include
问题描述
我正在尝试使用包含时过滤"的新功能,但由于某种原因我无法正确使用它.
但是以某种方式所有数据库中的6种产品被退回了
那是因为您要查询 _context.Product
.过滤后的 Include
用于过滤子集合,而不是主查询.因此,您可以获得所有产品,但所有这些产品应仅包含通过过滤器的类别.
您似乎希望EF仅返回具有包含"Vlees"类别的产品.以它们的名称命名,但这并不是过滤 Include
的目的.为此,您必须自己过滤产品:
_context.Product.Where(p => p.ProductCategories.Any(c => c.Category.Title.Contains(containsTitle)))
这可以与过滤后的 Include
结合使用,但不一定要结合使用.如果您不过滤包含
,则会按类别名称过滤产品,但将其类别中的所有类别都包含在内.
经过过滤的 Include
使您可以自由地分别过滤查询结果和子集合.
I'm trying to use the new function Filtered on Include but I'm not getting it right somehow. https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#preview-3
I got a product with categories. I need to filter Products on Category title/name. It's a many to many relations.
The category title should contain "Vlees". But somehow ALL 6 products in the database get returned, even with the wrong Category.Title name.
var products = await _context.Product
.Include(c => c.ProductCategories.Where(c => c.Category.Title.Contains(containsTitle)))
.ThenInclude(c => c.Category)
.ToListAsync();
But somehow ALL 6 products in the database get returned
That's because you're querying _context.Product
. Filtered Include
is for filtering child collections, not the main query. Therefore you get all products, but all of these products should only contain categories that pass the filter.
You seem to expect that EF only returns product that have categories containing "Vlees" in their names, but that's not the purpose of filtered Include
. To achieve that, you have to filter the products themselves:
_context.Product
.Where(p => p.ProductCategories.Any(c => c.Category.Title.Contains(containsTitle)))
This can be combined with the filtered Include
s, but not necessarily. If you don't filter the Includes
you get products filtered by category name, but containing all categories in their collections.
So filtered Include
gives you the freedom to filter the query result and child collections separately.
这篇关于ef core 5.0如何过滤包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!