'datetime2' error when using entity framework in VS 2010 .net 4.0

前端 未结 16 1173
半阙折子戏
半阙折子戏 2020-11-29 00:04

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

相关标签:
16条回答
  • 2020-11-29 00:49

    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.

    0 讨论(0)
  • 2020-11-29 00:49

    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.

    0 讨论(0)
  • 2020-11-29 00:49

    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.

    0 讨论(0)
  • 2020-11-29 00:49

    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 })
      
    0 讨论(0)
  • 2020-11-29 00:50

    When using Entity framework code first, declare it like this:

    public Nullable<System.DateTime> LastLogin { get; set; }
    
    0 讨论(0)
  • 2020-11-29 00:58

    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

    0 讨论(0)
提交回复
热议问题