views:

601

answers:

4

Hi, 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

+2  A: 

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

Jason Punyon
But I'm using a timestamp member.
Mohammadreza
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.
Jason Punyon
+1  A: 

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.

Adrian Grigore
+1  A: 

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

Eric J. Smith
A: 

Here's an generic Detach method.

Jo-wen