2009-11-06 92 views
0

我使用实体框架并使用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(); 

我是否正确添加关联?

回答

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(); 

希望这有助于

亚历