![](/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.