如何走出超范围转换错误使用的DbContext和SetInitializer修复DATETIME2?错误、超范围、DbContext、SetInitializer

2023-09-02 20:47:04 作者:月迷津度,何以忘言

我使用的是与实体框架4.1推出的DbContext和code首先的API。

I'm using the DbContext and Code First APIs introduced with Entity Framework 4.1.

在数据模型使用基本数据类型,如字符串的DateTime 。我使用的是在某些情况下,唯一的数据注解是 [必需] ,但这不是任何的的DateTime 属性。例如:

The data model uses basic data types such as string and DateTime. The only data annotation I'm using in some cases is [Required], but that's not on any of the DateTime properties. Example:

public virtual DateTime Start { get; set; }

在的DbContext子类也很简单,看起来像:

The DbContext subclass is also simple and looks like:

public class EventsContext : DbContext
{
    public DbSet<Event> Events { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Event>().ToTable("Events");
    }
}

在初始设置模型在今年或明年合理值的日期。

The initializer sets dates in the model to sensible values in either this year or next year.

然而,当我运行初始化,我得到这个错误在 context.SaveChanges()

However when I run the initializer, I get this error at context.SaveChanges():

一DATETIME2数据的转换   类型日期时间数据类型导致   在超出范围的值。该   语句已终止。

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

我不明白为什么会这样,因为在所有的一切就是这么简单。我也不知道如何解决它,因为没有EDMX文件进行编辑。

I don't understand why this is happening at all because everything is so simple. I'm also not sure how to fix it since there is no edmx file to edit.

任何想法?

推荐答案

您必须确保开始大于或等于SqlDateTime.MinValue(1753年1月1日) - 在默认情况下启动等于DateTime.MinValue(1月1日0001)。

You have to ensure that Start is greater than or equal to SqlDateTime.MinValue (January 1, 1753) - by default Start equals DateTime.MinValue (January 1, 0001).