Handling many-to-many Entities
I work with Entity Framework and with 2 many-to-many relationship entities. I get an error on SaveChanges() when I try to associate the entities:
Guid guid = new Guid();
FileLine fl = new FileLine();
guid.FileLines.Add(fl);
fl.Guids.Add(guid);
dc.FileLines.AddObject(fl);
dc.Guids.AddObject(guid);
开发者_StackOverflow中文版 dc.SaveChanges();
Am I adding the associations correctly?
Are you using POCO classes? Or standard EF generated classes?
If you are using standard EF generated classes you don't need to build the relationships in both directions, that is handled automatically for you.
So if you do this it should work:
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();
Hope this helps
Alex
精彩评论