2011-04-14 186 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