2

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

But I'm using a timestamp member.
It doesn't matter. It has to be detached from the original DataContext. The intent of the Attach() methods wasn't to move objects between datacontexts.
1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.