实体框架渴望加载过滤器

Sam*_*Sam 5 entity-framework eager-loading

我有一个简单的查询,我想这样做:

1)ProductsChildProducts哪些有PriceTiers
2)我想得到所有Productsa Category的a ID为1和Display= true.
3)我想包含所有ChildProductsDisplay= true的东西.
4)然后包括PriceTiershas IsActive= true.

根据我的阅读,EF不支持使用过滤器进行预先加载,因此以下内容不起作用:

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)))
Run Code Online (Sandbox Code Playgroud)

有什么建议?

ber*_*hof 9

从下往上开始,意思是,对PriceTier对象及其父项应用过滤器,并包括其父项(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
Run Code Online (Sandbox Code Playgroud)

(注意:priceTier =>在C#中与Function(priceTier)VB.NET中相同)

MergeOption理想情况下应该设置为执行查询以外的其他内容NoTracking.否则,EF将无法确保在查询结果集中多次出现的对象仅实现一次,例如a ProductChildProduct:

不需要的结果: PriceTier 1和2具有相同的父母,但父母已多次实现 - 每个PriceTier一次.

  • 产品1
    • ChildProduct 1
      • PriceTier 1
  • 产品1
    • ChildProduct 1
      • PriceTier 2

理想的结果: 设置MergeOption除了NoTracking获得这些结果之外的任何其他内容:

  • 产品1
    • ChildProduct 1
      • PriceTier 1
      • PriceTier 2