簡體   English   中英

實體框架-嘗試使用外鍵插入表中,EF嘗試使用主鍵插入原始表中

[英]Entity Framework - trying to insert into a table with a foreign key, EF attempts to insert into the original table with the primary key

在此處輸入圖片說明

嗨,這是我的數據庫圖。

我正在嘗試將行插入Order和OrderItem表中。 插入到訂單表很好。 但是,當我嘗試插入OrderItem表時,出現異常。 無法插入產品表,ProductId已存在。 為什么會這樣?

Insert code:

db.Orders.Add(newOrder);

db.SaveChanges();

newOrder.OrderItems = products.Convert(newOrder);

foreach (var orderItem in newOrder.OrderItems)
{
     db.OrderItems.Add(orderItem);
}

db.SaveChanges();

新的訂單對象已經具有一個訂單項列表,並且如果要插入的OrderItem記錄在產品表中沒有現有的productId,而沒有插入到Product表中,則僅需要一個例外(針對productId)。 如何解決?

交叉檢查訂單項列表是否具有Product實體對象,因為它是OrderItem表的外鍵。 您也可以嘗試在子表中顯式插入,例如先插入Order,然后使用應該使用Order實體對象的Order Items(注意OrderItem應該具有Product實體對象)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM