Inserting records containing timestamp columns in ADO.NET Entity Framework

In case you are playing with ADO.NET Entity Framework you might have seen that, by default, when you have timestamp columns in a new entity they are being inserted into the database when inserting and saving new entity. This behavior isn’t a correct one, since timestamps are server generated, and one gets a clear exception from SQL Server saying:

Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column.

This isn’t a bug in Entity Framework or something. It is rather a bug in EDW that doesn’t create correct definitions. The fix is rather simple:

  • open [yourefdefinition].ssdl file (formal description of the database)
  • find your timestamp columns, i.e.
  • <Property Name="COLUMNNAME" Type="timestamp" Nullable="false" />
  • add the attribute StoreGeneratedPattern=”computed” to each such column, i.e:
  • <Property Name="COLUMNNAME" Type="timestamp" Nullable="false" StoreGeneratedPattern="computed" />

That’s it. Make sure you rebuild your code, otherwise updated ssdl file won’t be copied to target folder* and application will load the old one.

More on the subject in this thread.

* Note: if you only change non compilable files (such as .ssdl and .msl ones but not .csdl – the later will invoke EntityModelCodeGenerator custom tool that will regenerate entity types and ObjectContext derived class that represents your database and thus force a rebuild) and re-run the application, IDE will know that your application files (compilable ones) weren’t modified and it won’t re-build the application – it will just run the application. As a collateral effect the modified files won’t be copied to target folder and your application will use the older ones.

Leave a Reply