我有一个简单的查询,我想这样做:
1) Products
有 ChildProducts
其中有 PriceTiers
2)我想得到所有的Products
有 Category
与 ID
1 和 Display
= 真的。
3) 然后我想包括所有 ChildProducts
有 Display
= 真的。
4) 然后包括 PriceTiers
有 IsActive
= 真的。
根据我的阅读,EF 不支持使用过滤器进行 Eager Loading,因此以下操作不起作用:
ProductRepository.Query.IncludeCollection(Function(x) x.ChildProducts.Where(Function(y) y.Display).Select(Function(z) z.PriceTiers.Where(Function(q) q.IsActive))).Where(Function(x) x.Categories.Any(Function(y) y.ID = ID)))
有什么建议?
最佳答案
从下往上开始,意思是在 PriceTier
上应用过滤器对象和它的 parent ,并包括它的 parent (C# 抱歉,但希望你明白这一点):
repository.PriceTiers
.Include("ChildProduct.Product") // eager load parents
.Where(priceTier =>
priceTier.IsActive &&
priceTier.ChildProduct.Display &&
priceTier.ChildProduct.Product.ID == 1 &&
priceTier.ChildProduct.Product.Display)
.AsEnumerable() // execute SQL statement
.Select(priceTier =>
priceTier.ChildProduct.Product) // return products rather than price tiers
(注意:C#中的
priceTier =>
与VB.NET中的Function(priceTier)
相同)MergeOption
理想情况下应该设置为 其他 比NoTracking
执行查询时。否则,EF 将无法确保在查询结果集中多次出现的对象仅被物化一次,例如 Product
或 ChildProduct
:不需要的结果:
PriceTier 1 和 2 具有相同的父级,但父级已多次具体化 - 每个 PriceTier 一次。
理想结果:
套装
MergeOption
除了 NoTracking
得到这些结果:关于entity-framework - Entity Framework 预加载过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5659317/