亲爱的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