2014-12-22 31 views
0

我在理解Linq和EF如何返回數據時遇到問題。我有三個簡單的類使用Linq返回EF6中的相關實體

產品, 材料, 文件

產品是由材料和材料具有文件。當我加載產品時,我想要返回產品組成材料的所有文檔。

這裏是我的課:

public class Product 
    {   
     public int Id { get; set; } 
     public string Name { get; set; } 
     ... 
     public ICollection<ProductMaterials> ProductMaterial { get; set; } 
    } 
    public class ProductMaterials 
    {   
     public int Id { get; set; } 

     public int ProductId { get; set; } 
     public Product Product { get; set; } 
     public int MaterialId { get; set; } 
     public Materials Material { get; set; } 
     ...   
    } 

public class Document 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    ... 
    public ICollection<MaterialDocument> MaterialDocument { get; set; } 
} 

public class MaterialDocument 
{ 
    public int Id { get; set; } 
    public int MaterialId { get; set; } 
    public Materials Material { get; set; } 
    public int DocumentId { get; set; } 
    public Document Document { get; set; } 
} 

加載材料及其相關文件時,我沒有任何問題。我使用此查詢:

var materialDocuments = db.MaterialDocuments 
            .Include("Document") 
            .Where(i => i.MaterialId == id) 
            .ToList(); 

如何加載產品與相關材料和材料的文件?我是否需要指向ProductMaterials的MaterialDocument類上的其他導航屬性?

+0

不知道如果有一個最大深度對於屬性路徑,但我認爲你可以做'.Include(「ProductMaterial.Material.MaterialDocument.Document」)' –

回答

1

要返回所有的Document記錄,你加載特定Product(獲得一個ID,我們會打電話給myProductID),只需做到以下幾點:

var product = db.Products.Find(myProductID); //The product that you're loading 
var documents = product.ProductMaterials.SelectMany(pm => 
         pm.Material.SelectMany(mat => 
          mat.MaterialDocuments.Select(matdoc => matdoc.Document))); 
+0

感謝@ IronMan84的建議。 SelectMany不適用於材質。但我可以添加MaterialDocuments,然後添加SelectMany。這是否代表缺少導航屬性? – andy