tags:

views:

39

answers:

2

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?

A: 

This is probably because you are maintaining a bidirectional relationship between o and its associated object. When you tell the DataContext to Insert o, its associated object is duplicated in the DataContext's object tracking graph (one time as loaded and another time as Insert for o).

Commenting out line 4 should resolve the issue, but leave you with a correct association between o and o.association.

Johannes Rudolph
Well, the weird thing is, the same exception is thrown when I comment either line 3 or 4. Only when I comment out both, I get no exception.
cdonner
I understand what you are saying, and I had the same suspicion, but I am pretty sure I am doing this in other places where I don't get this error. How else would I go about establishing a foreign key relationship for a new object ... ? Of course does the object on the other side already exist. Since I am loading it in the same DC before I establish the relationship, Linq should know that it already exists.
cdonner
This is actually a many-to-many association that I am trying to create.So, both objects exists, just the association needs to be inserted.
cdonner
It wasn't clear to me that both objects were actually transient (because one is new'ed up). If asking questions like this you should provide full detail so people can help you.
Johannes Rudolph
A: 

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.

cdonner