例如,有一个值表:
Id CarModel
1 Passat
2 Land Cruiser
并且需要添加不可为空的列制造商。 制造商的初始值(对于现有记录)应为:
For CarModel=Passat - VW
For CarModel=Land Cruiser - Toyota
etc.
我的迁移:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Manufacturer",
table: "Cars",
nullable: false);
}
我该怎么做?
答案 0 :(得分:2)
没有真正好的方法。您需要手动编辑生成的迁移,如下所示:
AddColumn
命令以首先将nullable
设置为true
(即 optional )来创建列。Sql
方法和原始SQL命令填充列。AlterColumn
命令以将列nullable
更改为预期的false
(即必需)。类似这样的东西:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Manufacturer",
table: "Cars",
nullable: true);
migrationBuilder.Sql(
@"UPDATE Cars SET Manufacturer = CASE CarModel
WHEN 'Passat' THEN 'VW'
WHEN 'Land Cruiser' THEN 'Toyota'
ELSE 'Other' END");
migrationBuilder.AlterColumn<string>(
name: "Manufacturer",
table: "Cars",
nullable: false,
oldClrType: typeof(string),
oldNullable: true);
}