How should I annotate CreateOn and ModifiedOn columns with EF 4.1?

In our database, each table has two DateTime columns, CreatedOn and ModifiedOn, set through triggers in SQL Server. CreatedOn is set to INSERT, and ModifiedOn is set to INSERT and UPDATE.

I am trying to use Entity Framework 4.1. How do I annotate / configure two properties?

I think this is due to the [DatabaseGenerated(DatabaseGeneratedOption.Computed)] annotation, but should I use this annotation for both, or should I set [DatabaseGenerated(DatabaseGeneratedOption.Identity)] in the CreatedOn field?

According to MSDN, Identification simply means that The database generates a value when a row is inserted. that seems true here.

Also, should I use [Timestamp] ?

+4
source share
1 answer

Use Identity for CreatedOn and Computed for ModifiedOn . Identity means that the value is set only during insertion and is returned back to the application. Computed installed during each modification (including insertion), and the value is returned back to the application after each performed insertion or update.

Just remember that none of these properties can be set in the application. Computed columns also cannot be part of the primary key or foreign key (this is not your case).

This will only work with an existing database. When using the first code, Computed can only be set for timestamp or rowversion .

timestamp used for optimistic concurrency. If you mark a column as a timestamp, each update will contain the WHERE timestampColum = @lastKnownValue . It will update the record only if the last known value matches the current value. If the value is different, you will get an exception. It is usually used with the timestamp SQL type. Using it with datatime will require some tests. The SQL datatime value does not match the value in .NET.

+8
source

Source: https://habr.com/ru/post/1346612/


All Articles