An attempt has been made to Attach or
Add an entity that is not new, perhaps
having been loaded from another
DataContext. This is not supported.
This is the error message I am getting when I try to run the following, roughly:
1 DataContext db = new DataContext();
2 o = new object();
3 o.association = db.GetAssociatedObject(pId);
4 db.objects.InsertOnSubmit(o);
5 db.SubmitChanges();
This code creates a new object, populates an association with an existing object, then inserts the new object. When I comment out line 3+4, the error goes away. What causes the error? Can I not do an insert with associated objects?
The error message is misleading. This is a bit more complicated, but I found the error.
I have a method that is trying to save a detached object, and create associations for it.
This method creates a new attached copy of the object and copies all the members. It then creates the association.
Say I have object A that is detached. My method tries to read it from database so that I have the attached version of it. Say this is object A. A is being updated with all the members that changed.
A needs to get an association with objects of type C, via a many-to-many relationship called B: A <= B => C
I assigned the detached copy of A to B. This caused the exception. Once I assigned the correct instance of A, it worked.