Sql – How to get to the bottom of this Linq to SQL error

linq-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.

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?

Best Answer

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.