默认值在 entity framework 代码首次迁移中不起作用

Default value does not work in entity framework code first migration

我偶然发现了一个 entity framework related question which I havn't found any answer for yet. When I try to add or alter a column while using code first migrations and set a default value for this column, I have the possibility to use either the defaultValue and/or the defaultValueSql 论点。

MSDN官方文档是这样写的:

ColumnModel.DefaultValue:

Gets or sets a constant value to use as the default value for this column.

ColumnModel.DefaultValueSql:

Gets or sets a SQL expression used as the default value for this column.

由于 Whosebug 上不同的默认值相关问题使用不同的方法,有人可以告诉我何时使用一种或另一种方法吗?

对于我的特定用例,我想为我的数据库列设置一个常量值 4,如下所示:

public override void Up()
{
    this.AddColumn("dbo.Foo", "Bar", c => c.Int(nullable: false, defaultValue: 4));
}

结果如下:

虽然这看起来完全正确,但数据行的所有值都设置为零...有谁知道,为什么?

编辑: 由于@Vidmantas Blazevicius 声明不会自动应用默认值,我尝试将以下代码添加到我的 Configuration class:

internal sealed class MigrationConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
    protected override void Seed(DatabaseContext context)
    {
        context.Database.ExecuteSqlCommand("UPDATE [dbo].[Foo] SET [Bar] = 4");
    }
}

但这也行不通。你们知道我在添加新列后如何设置默认值吗?

在向现有 table 添加新列时,不会为现有记录追溯添加默认值。

您可以使用 Add-Migration RunSqlScript 添加新的迁移步骤并使用自定义 Sql 更新新列中的值。