2012-07-04 32 views
0

我需要僅篩選類別中的可見產品,但它不起作用。Lambda表達式過濾包含與實體框架相關的數據

Category category = db.Categories 
      .Include(c => c.Products.Where(p => p.IsVisible)) 
      .First(c => c.CategoryID == 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.

UPDATE

var result = (from c in db.Categories 
          where c.CategoryID == id 
          select new 
          { 
           CategoryID = c.CategoryID, 
           Description = c.Description, 
           Products = (from p in db.Products 
              where p.IsVisible 
              && p.CategoryID == c.CategoryID 
              orderby p.DateSent descending 
              select p) 
          }).FirstOrDefault(); 

,但現在我需要的anonymousType投類別

+0

http://stackoverflow.com/questions/10035261/include-using- lambda表達式 –

回答

1

如果你希望你的查詢是沒有意義的:

the visibles products from a category

如果您真心希望在可見的產品,試試這個:

var visibleProducts = db.Categories 
         .Where(c => c.CategoryID == id) 
         .Select(c => c.Products.Where(p => p.IsVisible)); 

注:未經檢驗

+0

我會測試,但我需要類別數據加上可見產品列表 –

+0

您已經擁有該類別的ID,您可以將其作爲2個查詢。第一個查詢獲取該類別,第二個查詢從該類別獲取可見產品。這樣你有兩個。 – test

+0

我知道我可以使用2個查詢,但由於performece它會很高興使它只使用1. –

0

也許是這樣的:

var category = db.Products.Where(p=>p.IsVisible && p.CategoryID == id).Include("Category").ToList().Select(p=> p.Category).Distinct(); 

它可能不是因爲ToList的理想..但現在我看不到其他方式了。

也許你可以改變鮮明成FirstOrDefault()...

var category = db.Products.Where(p=>p.IsVisible && p.CategoryID == id).Include("Category").ToList().FirstOrDefault().Category; 

也不測試...