【问题标题】:Entity Framework Seed Method DateTime Error When DateTime Column Is NullableDateTime 列可为空时的实体框架种子方法 DateTime 错误
【发布时间】:2014-06-22 01:19:54
【问题描述】:

我有以下 POCO:

public class Specialty
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? CreatedDate { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
    public string Name { get; set; }
}

在 Configuration.cs 的种子方法中,我有:

public override void Seed(MyContext context)
{
      context.Specialties.AddOrUpdate(p => p.Name,
                new Specialty { Id = Guid.NewGuid().ToString(), 
                                Description = "Allergy and Immunology", 
                                Name = "Allergy and Immunology" },
                new Specialty { Id = Guid.NewGuid().ToString(), 
                                Description = "Anaesthesiology",
                                Name = "Anaesthesiology" });
}

此表的迁移“命令”:

CreateTable("dbo.Specialty",
            c => new
                {
                    Id = c.String(nullable: false, maxLength: 128),
                    CreatedDate = c.DateTime(defaultValueSql: "GETDATE()"),
                    Description = c.String(),
                    Name = c.String(),
                })
            .PrimaryKey(t => t.Id);

因此,在 Seed 函数中,我故意省略了 CreatedDate,因为我认为由于我的注释(数据库生成、计算)和迁移设置 defaultValueSql: "GETDATE()",SQL 会在插入时负责填充它。

我收到错误消息“将 datetime2 数据类型转换为 datetime 数据类型导致值超出范围。”当我运行更新数据库时。据我所知,未在 Seeding 方法中指定 CreatedDate 将尝试将空 CreatedDate 保存到数据库中,这是允许的。看来 EF 在我背后做了什么 - 什么?

我的猜测是 EF 强制 DateTime.Now.Min 或超出 SQL datetime 数据类型范围的东西...但是由于我指定了生成的数据库,它不应该阻止 EF 创建一个插入的值超出范围?

【问题讨论】:

    标签: c# sql entity-framework datetime


    【解决方案1】:

    以上内容,如发布的那样确实有效。但是,如果出现以下情况,我们会收到此错误:

    1. 除了 CreatedDate 之外,我们还有一个不可为空的 DateTime 属性,我们可能错过了它,并且没有在 Seed 方法中指定。
    2. 很容易忘记:如果您使用自定义属性创建了自定义 AspNet.Identity 实体,您可能在其中放置了一个不可为空的 DateTime 属性,就像我的情况一样。

    【讨论】:

    • 所以你的 POCO 没有发布,你的迁移代码也没有发布?
    【解决方案2】:

    我相信这回答了您的问题。 datetime2 不允许 DateTime.Min 但 DateTime 允许。 DateTime.min 值为 00:00:00.0000000,0001 年 1 月 1 日。

    链接详情。

    Conversion of a datetime2 data type to a datetime data type results out-of-range value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2015-06-12
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      相关资源
      最近更新 更多