我使用Entity Framework和2个多对多关系实体。当我尝试关联实体时,我在SaveChanges()上收到错误:
Guid guid = new Guid();
FileLine fl = new FileLine();
guid.FileLines.Add(fl);
fl.Guids.Add(guid);
dc.FileLines.AddObject(fl);
dc.Guids.AddObject(guid);
dc.SaveChanges();
我是否正确添加了关联?
答案 0 :(得分:1)
您使用的是POCO课程吗?或标准EF生成的类?
如果您使用的是标准的EF生成类,则无需在两个方向上建立关系,而是自动为您处理。
所以,如果你这样做,它应该有效:
Guid guid = new Guid();
FileLine fl = new FileLine();
guid.FileLines.Add(fl);
// fl.Guids.Add(guid); -- not needed - the previous line does this automatically
dc.FileLines.AddObject(fl);
// dc.Guids.AddObject(guid); -- not needed - the previous line adds the guid too.
dc.SaveChanges();
希望这有帮助
亚历