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: 256

Filed under:
|

I've been getting several errors:

  1. cannot add an entity with a key that is already in use

  2. 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:

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

  2. Would most people recommend that moving the datacontext to the class wide scope is desirable for web pages?

© Stack Overflow or respective owner

Related posts about linq-to-sql

Related posts about ASP.NET