Graeme Hill's Dev Blog

LINQ to SQL Gotcha #4: ChangeConflictException on Update of Manually Attached Data

Star date: 2010.040

LINQ to SQL has built in optimistic concurrency checking. When you create an unattached entity and then attach it (ie: with the Attach() function) the concurrency check will always fail by throwing a ChangeConflictException unless one of the two are true:

  • The table that the entity belongs to has a timestamp column and its value is exactly the same as it appears in the database.
  • There is no timestamp column but the "no count" feature on SQL Server is off.

Using a timestamp column seems like the more elegant solution, but it does require that you know the timestamp value. This usually means that if you're attaching the result of a stored procedure so that you can save back the results, your stored procedure needs to return the timestamp in addition to the primary key.