c# - DateTime 列可为空时 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; 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 数据类型转换为 datetime 数据类型导致值超出范围。”当我运行更新数据库时。据我所知,不在 Seeding 方法中指定 CreatedDate 将尝试将 null CreatedDate 保存到数据库中,这是允许的。好像 EF 在我背后做了什么 - 什么?

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

最佳答案

我相信这可以回答您的问题。 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

关于c# - DateTime 列可为空时 Entity Framework 种子方法 DateTime 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23477566/

相关文章:

asp.net - 带有外部 connectionStrings.config 文件的 WebPublish Code-First 迁移

.NET ORM 需要虚拟,不能处理密封?

mysql - 尝试选择以特定字母开头和结尾的对象

sql - 在通过 sql server 作业执行 ssis 包的运行时将 run 64 位运行时属性更改为 false

sql - 按字段排序,以字母开头

c# - 即使定义了其他主键, Entity Framework 6 也会创建 Id 列

c# - 路径组合问题

c# - c#中显式接口(interface)实现和隐式接口(interface)实现有什么区别

c# - 将程序集转换为 byte[]

c# - 将对象列表插入 SQL Server 表