C# 当DateTime列可为空时,实体框架种子方法DateTime错误
我有以下POCO:C# 当DateTime列可为空时,实体框架种子方法DateTime错误,c#,sql,entity-framework,datetime,C#,Sql,Entity Framework,Datetime,我有以下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; s
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()”
当我运行Update Database时,我收到一个错误:“将datetime2数据类型转换为datetime数据类型导致值超出范围。”。据我所知,不在种子设定方法中指定CreatedDate将尝试将空CreatedDate保存到数据库中,这是允许的。好像EF在我背后做了什么-什么
我的猜测是EF forced DateTime.Now.Min或超出SQL DateTime数据类型范围的内容。。。但既然我指定了database generated,它是否应该阻止EF为insert创建超出范围的值呢?我相信这回答了您的问题。datetime2不允许DateTime.Min,但DateTime允许。DateTime.min值为00:00:00.00000000101年1月1日 链接到详细信息。
上面的帖子实际上是有效的。但是,如果:
那么您的POCO没有发布,您的迁移代码也没有发布?