gpt4 book ai didi

c# - DateTime 列可为空时 Entity Framework 种子方法 DateTime 错误

转载 作者:行者123 更新时间:2023-11-30 17:48:10 27 4
gpt4 key购买 nike

我有以下 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com