C# – Linq to SQL Insert Error

clinq-to-sql

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?

Best Answer

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.