Getting this error:
System.Data.SqlClient.SqlException : The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range v
If you are using Code First you must declare any optional DateTime
property as DateTime?
or Nullable<DateTime>
. Unset DateTime
objects can cause issues.
If the property is nullable in the database and a standard DateTime
in code (not DateTime?
), ADO.NET will send an insert command with a date of 0001-01-01 (not NULL
), but the minimum SQL DateTime value is 1753-01-01, causing an error. If your DateTime
property in the code is nullable (e.g. DateTime?
or Nullable<DateTime>
), the insert command is will attempt to insert a NULL
instead of an out-of-range date.
Is there ModifiedTime property in your entity, which is updated on the database side only? If so, you must use DatabaseGeneratedOption.Computed (for EF CodeFirst). Also visit this https://stackoverflow.com/a/9508312/1317263
Thank you.
After trying to solve this issue for several days I used DateTime?
as the datatype in my model with Entity Framework Code-First instead of DateTime
.
Two solutions:
Declare the properties in your class like below and make an update-database:
public DateTime? MyDate {get; set;}
Or set a date for the property in the Seed method that populates the database, no need of update-database :
context.MyClass.AddOrUpdate(y => y.MyName,new MyClass { MyName = "Random", MyDate= DateTime.Now })
When using Entity framework code first, declare it like this:
public Nullable<System.DateTime> LastLogin { get; set; }
Whatever fits in a datetime will fit in a datetime2 data type, vice versa this is not the case, you can stick a date of January 1500 in a datetime2 data type but datetime only goes back to 1753, a datetime2 column can go back all the way to the year 1. I would check what the min date that you are passing in is and if your tables have datetime2 or datetime data type columns