I started using EF code-first recently and added a DateTime field to an entity that I wanted to create in my database. I could add the property to my class without compilation issues but got an error when I used “update-database” in my Package Manager console. the error I got was
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value”.

This was weird and after some research I found out that EF was generating an INSERT with the default DateTime value of 01/01/0001, which is invalid for SQL’s DATETIME type but permitted for SQL 2008′s DATETIME2 type.
What we want is to exclude this fields when sending the INSERT (and UPDATE) statements.

This is done by adding an attribute to this property.
The exact attribute to add is
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
and this tells EF that this field is computed later and should not be used in the INSERT statement.

This attribute is in the System.ComponentModel.DataAnnotations namespace to be used into your class files.

Another useful attribute for an identity field is:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
which tells EF to not use this field in INSERTs. This is useful when you do not have a field named Id or a Primary Key.

Advertisements