[英]Entity Framework 3.5 Many-to-Many update issue
尊敬的StackOverflow社區,
我在更新EF 3.5中的多對多關系時遇到問題:
但首先,在這里您可以看到我的表格:
Table "Message":
ID, int (primary key)
Message, string
Table "DisplayDestinations":
ID, int (primary key)
Destination, string
My DisplayDestinations are:
ID;Destination:
1;PC
2;Mobile
3;Printer
4;PDF
我想您可以想象一個“消息”可以具有多個DisplayDestinations。
我可以插入和刪除“消息”或單個“ DisplayDestinations”。 但是,如果我想更新它們,則會出現錯誤。
EF 3.5想要創建一個新的“ DisplayDestinations”,但是我沒有任何代碼行可以執行此操作...
這是我的更新方法。 可能不方便解決,但是為什么我不能更新它:
List<DisplayDestinations> CorrectMDfromMDs = new List<DisplayDestinations>(); // Holds the real DisplayDestinations with the right ID and Destination
foreach (Message item in Messages)
{
// Get all DisplayDestinations with the EntityState Added or Modified to know which to add.
var ChangedMDs = item.DisplayDestinations.Where(x => x.EntityState == System.Data.EntityState.Added || x.EntityState == System.Data.EntityState.Modified);
foreach (MD md in ChangedMDs)
{
CorrectMDfromMDs.Add(DBService.GetMDs().FirstOrDefault(x => x.ID == md.ID));
}
// delete the DisplayDestinations from the Message which modified or added state, because they aren't the right from my DisplayDestinations
while (ChangedMDs.Count() > 0)
{
item.MDs.Remove(ChangedMDs.ElementAt(0));
}
// Add the right DisplayDestinations to the Message
foreach (var md in CorrectMDfromMDs)
{
item.MDs.Add(md);
}
CorrectMDfromMDs.Clear();
}
DBService.SaveChanges();
之后,我得到一個例外,即DisplayDestinations的Destination不能為NULL。 我認為EF 3.5試圖在DisplayDestinations中添加新的DisplayDestination,但是為什么呢?
我已經嘗試過此“ 插入/更新多對多實體框架”。 我該怎么做? 但沒有成功。
先感謝您!
您在(x => x.ID == md.ID)上調用FirstOrDefault
我猜測添加的EntityState.Added尚不存在於數據庫中。 並且它們是從Linq表達式返回null(默認值)的參數。
如果不是多余的原因來解釋CorrectMDfromMDs,現在其中有一些Null項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.