![](/img/trans.png)
[英]EF6 - error when insert entity with related entites only by navigation property
[英]Returning Related Entites in EF6 with Linq
我在了解Linq和EF如何工作以返回数据时遇到问题。 我有三个简单的课程
产品,材料,文件
产品是由材料组成的,并且有文件的材料。 加载产品时,我想退回构成该产品的物料的所有文档。
这是我的课程:
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();
如何为产品加载相关物料和物料文档? 我是否需要在MaterialDocument类上指向ProductMaterials的其他Navigation属性?
要返回您正在加载的特定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.