linq-to-sql "an attempt has been made to attach or add an entity that is not new"?
Posted
by Curtis White
on Stack Overflow
See other posts from Stack Overflow
or by Curtis White
Published on 2010-05-12T15:42:11Z
Indexed on
2010/05/12
15:44 UTC
Read the original article
Hit count: 284
linq-to-sql
|ASP.NET
I've been getting several errors:
cannot add an entity with a key that is already in use
An attempt has been made to attach or add an entity that is not new, perhaps having been loaded from another datacontext
In case 1, this stems from trying to set the key for an entity versus the entity. In case 2, I'm not attaching an entity but I am doing this:
MyParent.Child = EntityFromOtherDataContext;
I've been using using the pattern of wrap everything with a using datacontext. In my case, I am using this in a web forms scenario, and obviously moving the datacontext object to a class wide member variables solves this.
My questions are thus 2 fold:
How can I get rid of these errors and not have to structure my program in an odd way or pass the datacontext around while keeping the local-wrap pattern? I assume I could make another hit to the database but that seems very inefficient.
Would most people recommend that moving the datacontext to the class wide scope is desirable for web pages?
© Stack Overflow or respective owner