C# – Linq to Sql – Reattach and Update an entity

If you’d listen to Microsoft, you’d believe than in Linq to SQL, you can’t reattach a changed entity to a new DataContext and submit the changed entity to the database. Well this isn’t true. It can be done with a little bit of foresight.

The first step is to make sure that the underlying table has a timestamp column. Then you need to make sure that the entity object takes this into account. For this you should only create the entity in Visual Studio’s designer after the timestamp column has been added. If it already exists, delete it from the designer, then drop it from the Server Explorer to the designer again.

Now that this basic infrastructure is in place, you only need to make sure that when you get an entity from a DataContext, and that entity will be updated and reattached to another DataContext later, the initial DataContext should have the EnableDeferredLoading set to false. You can then reattach to the second DataContext with the Attach(T entity, bool isUpdated) method and submit the object.


Product product;

using (var db = new MyDataContext())
    db.DeferredLoadingEnabled = false;
    product = db.Products.SingleOrDefault(p => p.Id = "1");

product.Name = "Updated Name";

using (var db = new MyDataContext())
    db.Attach(product, true);

Voilà, you are done!