mrtaikandi
mrtaikandi

Reputation: 6948

Problem attaching an entity in LINQ to SQL

I'm trying to attach an entity in LINQ to SQL but it throws the following exceptionL:

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.

<Table Name="dbo.Products" Member="Products">
    <Type Name="Product">
      <Column Name="Id" Type="System.Int64" DbType="BigInt NOT NULL IDENTITY" IsReadOnly="true" IsPrimaryKey="true" IsDbGenerated="true" CanBeNull="false" />
      <Column Name="Name" Type="System.String" DbType="NVarChar(MAX) NOT NULL" CanBeNull="false" />    
      <Column Name="IsDeleted" Type="System.Boolean" DbType="Bit NOT NULL" CanBeNull="false" />
      <Column Name="Timestamp" Type="System.Data.Linq.Binary" DbType="timestamp NOT NULL" CanBeNull="false" IsVersion="true" />
      {...SOME ASSOCIATIONS....}
    </Type>
</Table>

The code I use to attach the entity is:

var context = new MyDataContext();
context.Products.Attach(entity, true);

Any idea, why I get this error? Thanks

Upvotes: 2

Views: 1196

Answers (3)

Adrian Grigore
Adrian Grigore

Reputation: 33318

I guess you ran into this problem because you are trying to to use LINQ2SQL in an n-tier environment, probably with ASP.NET so that the old context is not existant anymore when you are trying to commit changes to the database?

I've had exactly the same problems and solved them by writing a generic Repository implementation for the data layer. It takes care of all entity detach / attach issues and even supports update and deleting entity detached trees and might help you write your data layer with less effort. You can find a closer description and the source code here.

Upvotes: 1

Eric J. Smith
Eric J. Smith

Reputation: 971

PLINQO implements Detach functionality on your entities automatically as well as a ton of other features and enhancements. If you are interested, check out http://www.plinqo.com

Upvotes: 1

You can attach an entity to a DataContext different from the one from which it was created only if it has been serialized and deserialized first (Say sending it to the client and having it come back).

See here for more

Upvotes: 2

Related Questions