【发布时间】: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