親愛的StackOverflow社區,實體框架3.5多到很多更新的問題
我必須更新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目標不能爲空。我認爲EF 3.5試圖在DisplayDestinations中添加一個新的DisplayDestination,但爲什麼?
我試過這個Insert/Update Many to Many Entity Framework . How do I do it?但沒有成功。
預先感謝您!
嘿eran otzap,謝謝你的回答,但我認爲你錯了。因爲當沒有任何匹配時,FirstOrDefault返回null。而其他循環則不會迭代,因爲它們是空的。或者我弄錯你了嗎?你會建議如何解決這個問題? – GrayFox 2014-09-01 20:14:22
1)您選擇全部添加和修改。 2)U跑過它們問.FirstOrDefault(x => x.ID == md.ID)。 3)被添加的人不會退出數據庫,所以他們沒有找到和Linq爲您返回空值。 4)然後你把這個null放在CorrectMDfromMDs中。 – 2014-09-02 14:22:37