views:

23

answers:

1

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);
                            dc.SaveChanges();

Am I adding the associations correctly?

+1  A: 

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

Alex James