2011-04-14 190 views
2

我使用下面的表达式:实体框架4.1 - 选择

ProductRepository.Query.Include(Function(x) x.ChildProducts.Select(Function(y) y.PriceTiers.Where(Function(z) z.IsActive))).Where(Function(x) x.Categories.Any(Function(y) y.ID = ID)) 

而且收到此错误:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. 

如果我删除此:

.Where(Function(z) z.IsActive) 

它工作正常,但我需要过滤不活动的价格层。

任何想法?

更新

这里是我的解决方案:

Public Function GetProductsByCategoryID(ID As Integer) As System.Collections.Generic.IEnumerable(Of Core.Entities.Product) Implements Core.Interfaces.IProductService.GetProductsByCategoryID 
     Dim Col = ProductRepository.Query.Where(Function(x) x.Display AndAlso x.Categories.Any(Function(y) y.ID = ID)) _ 
        .Select(Function(x) New With { _ 
           .Product = x, 
           .ChildProducts = x.ChildProducts.Where(Function(y) y.Display).Select(Function(y) New With { _ 
                             .ChildProduct = y, 
                             .PriceTiers = y.PriceTiers.Where(Function(z) z.IsActive) 
                            }) 
          }).ToList.Select(Function(x) x.Product) 

     Return Col 

    End Function 

回答

3

你不能这样做,在没有投影或单独的查询来加载导航属性单一查询。对于Include的Lambda表达式仅接受引用的点符号和集合的Select,但不能执行任何过滤。

过滤可以在单独的查询中使用的DbContext API时:

var data = context.Entry(product) 
        .Collection(p => p.ChildProducts) 
        .Query() 
        // Here are your filters 
        .Load(); 

编辑:

投影要求是这样的:

var data = context.Products 
        .Where(...) 
        .Select(p => new 
         { 
          Product = p, 
          ChildProducts = p.ChildProducts.Where(...) 
         }); 
+0

@Lad - 谢谢! – Sam 2011-04-14 15:41:02

+0

@Lad - 所以这假设你有一个产品正确行事?如果是这样,你将如何做到这一点与产品集合? – Sam 2011-04-14 16:01:07

+1

它不适用于收集。您必须改用投影来使用自定义查询。 – 2011-04-14 16:16:47