[英]EF - Many To Many INSERT
我必須在一張表中插入記錄,並在帶有兩個 FK 的多對多表中插入記錄。
我有: 產品 1<=>n 產品_供應商 n<=>1 供應商
產品:ID、名稱、代碼 Products_Supplier:ID、ID_Products、ID_Supplier、可用性、活動、價格、品牌 供應商:ID、名稱、站點
供應商列表已經有數據,無需在那里添加任何內容。
我必須在 Product 和 Product_Supplier 中添加數據,其中 Product_Supplier 需要添加產品的 ID 以及我要添加的數據:可用性、活動和價格。 Product_Supplier 還需要供應商的 id。 這是我到目前為止所做的,但它給出了驗證錯誤:
Products_Supplier.ID_Supplier= supplier.Id;
Products_Supplier.Products.Name= record.productsVM.Name; //insert product name
Products_Supplier.Availability = record.productsVM.Availability; //here shud insert availability of the product inserted before
Products_Supplier.Active = record.productsVM.Active;
Products_Supplier.Brand = record.productsVM.Brand;
dbContext.Products_Supplier.Add(Products_SupplierObj);
dbContext.SaveChanges();
如果有任何疑問,請詢問他們。
如果您遵循實體框架約定,您將擁有這樣的類
class Product
{
public int Id {get; set;}
public string Name {get; set;}
... // other properties
// Every Product is supplied by zero or more Suppliers (many-to-many)
public virtual ICollection<Supplier> Suppliers {get; set;}
}
class Supplier
{
public int Id {get; set;}
public string Name {get; set;}
... // other properties
// Every Supplier supplies zero or more Products (many-to-many)
public virtual ICollection<Product> Products{get; set;}
}
在實體框架中,表的列由非虛擬屬性表示。 虛擬屬性表示表之間的關系:一對多、多對多、...
因為你在關系的兩邊都使用了virtual ICollection<...>
,實體框架知道你設計了一個多對多的關系並且會為你創建連接表,即使你沒有提到它。
現在顯然您有一個現有的供應商和現有的產品,並且您希望供應商提供此產品:只需將其添加到virtual ICollection<...>
Supplier supplier = dbContext.Suppliers.Where(...).FirstOrDefault();
Product product = dbContext.Products.Where(...).FirstOrDefault();
// The Supplier will supply this product.
supplier.Products.Add(product);
// or the Product will be supplier by the supplier:
product.Suppliers.Add(supplier);
可能是屬性 Products 為空。 在這種情況下:
supplier.Products = new Product[] {product};
如果您想添加新產品並讓供應商提供:
supplier.Products.Add(new Product
{
Name = ...,
... // other Product properties
});
不要填充主鍵或外鍵。 當您 SaveChanges 時,它們將由數據庫填充
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.