[英]Entity Framework Seed Method DateTime Error When DateTime Column Is Nullable
我有以下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,因为我认为SQL会在插入时填充它,因为我的注释(数据库生成,计算)和迁移设置defaultValueSql: "GETDATE()"
。
我收到该错误“将datetime2数据类型转换为日期时间数据类型导致超出范围的值。” 当我运行Update-Database时。 据我所知,未在Seeding方法中指定CreatedDate将尝试将null CreatedDate保存到数据库中,这将被允许。 看起来EF在我背后做了什么 - 什么?
我的猜测是EF强制DateTime.Now.Min或SQL日期时间数据类型超出范围的东西......但是因为我已经指定了数据库生成,所以不应该阻止EF创建一个out-of - 插入的范围值?
我相信这回答了你的问题。 datetime2不允许DateTime.Min,但DateTime不允许。 DateTime.min值是0001:00年1月1日00:00:00.0000000。
以上,发布实际上有效。 但是,如果出现以下情况我们会收到此错
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.