Entity Framework Core:将可为空列迁移到必需列时的默认值

xer*_*him 4 c# sql-server entity-framework entity-framework-core .net-core

我有一个datetime2专栏,以前是nullable
我们现在需要设置此列,因此我们希望根据需要进行设置,并使用默认值 1970-1-1 迁移该列。

我已创建迁移并将迁移文件编辑为以下内容:

protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterColumn<DateTime>(
            name: "Start",
            table: "Project",
            nullable: false,
            oldClrType: typeof(DateTime),
            oldType: "datetime2",
            oldNullable: true, 
            defaultValue: new DateTime(1970, 1, 1));
    }
Run Code Online (Sandbox Code Playgroud)

我已经手动添加了该defaultValue: new DateTime(1970, 1, 1));行。

不幸的是,在更新数据库时出现以下错误:

2021-03-22 10:12:55.5398:“UpdateDatabase”中发生错误:Microsoft.Data.SqlClient.SqlException(0x80131904):无法将值 NULL 插入表“dbo.Project”的“Start”列;列不允许为空。更新失败。该语句已终止。

我也尝试通过设置值,defaultValueSql但出现了同样的错误:

defaultValueSql: "'1970-1-1'"
Run Code Online (Sandbox Code Playgroud)

为什么 defaultValue 不起作用,我做错了什么吗?

提前致谢

顺便说一句:这是执行的脚本:

DECLARE @var0 sysname;
SELECT @var0 = [d].[name]
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[Project]') AND [c].[name] = N'Start');
IF @var0 IS NOT NULL EXEC(N'ALTER TABLE [Project] DROP CONSTRAINT [' + @var0 + '];');
ALTER TABLE [Project] ALTER COLUMN [Start] datetime2 NOT NULL;
ALTER TABLE [Project] ADD DEFAULT '1970-01-01T00:00:00.0000000' FOR [Start];
Run Code Online (Sandbox Code Playgroud)

Maj*_*vin 6

如果要required在数据库中创建现有列,则需要确保该列中没有空值。为了解决这个问题,请更新表并用值填充该列。

migrationBuilder.Sql("UPDATE Project SET Start = GETDATE() WHERE Start is null");
 migrationBuilder.AlterColumn<DateTime>(
        name: "Start",
        table: "Project",
        nullable: false,
        oldClrType: typeof(DateTime),
        oldType: "datetime2",
        oldNullable: true, 
        defaultValue: new DateTime(1970, 1, 1));
Run Code Online (Sandbox Code Playgroud)