简体   繁体   English

使用Linq返回EF6中的相关实体

[英]Returning Related Entites in EF6 with Linq

I am having a problem understanding how Linq and EF are working to return data. 我在了解Linq和EF如何工作以返回数据时遇到问题。 I have three simple classes 我有三个简单的课程

Products, Materials, Documents 产品,材料,文件

Products are made up of materials and materials have documents. 产品是由材料组成的,并且有文件的材料。 When I load a product, I want to return all the documents for the materials that product is made up from. 加载产品时,我想退回构成该产品的物料的所有文档。

Here are my classes: 这是我的课程:

    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; }
}

I am not having any issues when loading a material and its related documents. 加载材料及其相关文档时,我没有任何问题。 I use this query: 我使用以下查询:

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

How can I load Product with related Materials and the Material's documents? 如何为产品加载相关物料和物料文档? Do I need additional Navigation properties on the MaterialDocument class pointing back to ProductMaterials? 我是否需要在MaterialDocument类上指向ProductMaterials的其他Navigation属性?

To return all of the Document records for a specific Product that you're loading (given an ID we'll call myProductID ), just do the following: 要返回您正在加载的特定Product所有Document记录(给定一个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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM