.NET CORE 2.1.1 with Entity Framework Core 2.1.4 代码优先:从字符串转换日期 and/or 时间时转换失败
.NET CORE 2.1.1 with Entity Framework Core 2.1.4 Code First: Conversion failed when converting date and/or time from character string
我有一个扩展方法可以在创建后为我的 table 播种:
public static class ModelBuilderExtensions
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<AppUser>(entity =>
{
entity.HasData(
new Event() { id = 1, WhenDate = DateTime.Now.AddMonths(1) }
)
}
}
我用这个命令创建了迁移文件
Add-Migration InitialCreate
然后
Update-Database
用table创建数据库但是我有这个错误:
Conversion failed when converting date and/or time from character
string
在我的 InitialCreate 文件中有这一行:
WhenDate = table.Column(type: "datetime", nullable: false)
在我的控制台日志中,在 insert into 命令中,我看到了这个字符串:
'2019-03-12T16:09:33.617+01:00'
我猜字符串格式不正确,但如何更改呢?什么是正确的格式?
谢谢
我找到了一个解决方案,如果我用 UtcNow
替换 Now
就可以了!因为它删除了“+01:00”...
替换
DateTime.Now.AddMonths(1)
来自
DateTime.UtcNow.AddMonths(1)
字符串结果:
'2019-03-12T17:08:25.682Z'
对我来说,当我尝试在 运行 update-database:
之后更改列时会发生这种情况
我通过添加手动默认值来修复,例如:
默认值:“0001-01-01”
例如:
migrationBuilder.AddColumn<DateTime>(
name: "OperationDateTime",
schema: "DefinitionContext",
table: "Path",
type: "DateTime",
nullable: false,
defaultValue:"0001-01-01");
我有一个扩展方法可以在创建后为我的 table 播种:
public static class ModelBuilderExtensions
{
public static void Seed(this ModelBuilder modelBuilder)
{
modelBuilder.Entity<AppUser>(entity =>
{
entity.HasData(
new Event() { id = 1, WhenDate = DateTime.Now.AddMonths(1) }
)
}
}
我用这个命令创建了迁移文件
Add-Migration InitialCreate
然后
Update-Database
用table创建数据库但是我有这个错误:
Conversion failed when converting date and/or time from character string
在我的 InitialCreate 文件中有这一行:
WhenDate = table.Column(type: "datetime", nullable: false)
在我的控制台日志中,在 insert into 命令中,我看到了这个字符串:
'2019-03-12T16:09:33.617+01:00'
我猜字符串格式不正确,但如何更改呢?什么是正确的格式?
谢谢
我找到了一个解决方案,如果我用 UtcNow
替换 Now
就可以了!因为它删除了“+01:00”...
替换
DateTime.Now.AddMonths(1)
来自
DateTime.UtcNow.AddMonths(1)
字符串结果:
'2019-03-12T17:08:25.682Z'
对我来说,当我尝试在 运行 update-database:
之后更改列时会发生这种情况我通过添加手动默认值来修复,例如: 默认值:“0001-01-01”
例如:
migrationBuilder.AddColumn<DateTime>(
name: "OperationDateTime",
schema: "DefinitionContext",
table: "Path",
type: "DateTime",
nullable: false,
defaultValue:"0001-01-01");