Sql – Problem attaching an entity in LINQ to SQL

linq-to-sqlnet

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

Best Answer

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