tags:

views:

43

answers:

1

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.

Having worked with Linq to SQL for some time, I believe that I know about its limitations and that I follow the rules when I write new code. But it is frustrating to get this exception, as there is no indication of which object caused the violation. In complex data manipulation scenarios with multiple DCs, I can only think of trial-and-error to narrow down the possible culprits. Is there a way to find out more?

A: 

If you attach an object to your DataContext, it must have been created by you using the new operator. If you read the object from a DataContext, you must save it to the same DataContext.

To alleviate these kinds of problems, I always use a single DataContext, and I do everything on a "unit of work" basis.

Generally speaking, that means that, at any given time, I am reading the records I need, performing work on those records, and saving changes, all in a single unit of work, using a single DataContext. Since it is a unit of work, it doesn't bleed over into other DataContext objects.

If Linq to SQL is fighting you on this, I would examine your architecture and see if the way you are doing it is optimal, especially if you are finding it difficult to identify the object causing the error. In general it is difficult to share objects between DataContexts. You can do it (using things like "attach" and "detach"), but it's a pain in the ass.

Robert Harvey
I have not found a way around re-attaching detached objects in a stateful web application. I have a reliable solution for the that. In this case here, I am trying to do "sub units" of work that manipulate data obtained by a master data context. It seems that this is not possible. If I load an entity in one data context, then make changes to it in another data context, I get this error in the final SubmitChanges(). it seems I will have to make sure that each "subunit" of work handles everything on its own. Thanks for your suggestions.
cdonner
You can pass your original DataContext as a parameter to your sub-units, if you still want to use the original data objects. But yes, I generally agree with the premise that the sub-units be self-contained.
Robert Harvey
I solved the problem by doing exactly that, but I would still be curious to know if there is a way to find out what object caused this exception.
cdonner
Not that I know of. You would have to sprinkle SubmitChanges() calls through your code until you were able to bracket the object that is the culprit.
Robert Harvey