ef core修改主键类型相关删除外键索引约束以及重建过程

一般的字段修改类型直接修改,然后add-migration, update-database,没什么问题,但是主键的话,直接修改会报错,如果表的主键

作为另一个表的外键的话,更会报错

约束 'PK_ProcessRatio' 正由表 'MaterialCost' 的外键约束 'FK_MaterialCost_ProcessRatio_ProcessRatioId' 引用。
未能删除约束。请参阅前面的错误信息。

The object 'PK_ProcessRatio' is dependent on column 'ProcessRatioId'.

The object 'FK_MaterialCost_ProcessRatio_ProcessRatioId' is dependent on column 'ProcessRatioId'.

ALTER TABLE ALTER COLUMN ProcessRatioId failed because one or more objects access this column.

这些都是因为有约束的关系,所以我们在add-migration后,需要自行修改up()的那个方法

protected override void Up(MigrationBuilder migrationBuilder)
{


migrationBuilder.AlterColumn<string>(
name: "ProcessRatioId",
table: "ProcessRatio",
type: "char(4)",
nullable: false,
oldClrType: typeof(string));

migrationBuilder.AlterColumn<string>(
name: "ProcessRatioId",
table: "MaterialCost",
type: "char(4)",
nullable: true,
oldClrType: typeof(string),
oldNullable: true);


}
这个是直接生成的代码,运行update-database会报错。需要做如下修改

protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_MaterialCost_ProcessRatio_ProcessRatioId",
table: "MaterialCost");//删除外键

migrationBuilder.DropIndex(
name: "IX_MaterialCost_ProcessRatioId",
table: "MaterialCost");//删除索引

migrationBuilder.DropPrimaryKey(//删除主键
name: "PK_ProcessRatio",
table: "ProcessRatio");

migrationBuilder.AlterColumn<string>(
name: "ProcessRatioId",
table: "ProcessRatio",
type: "char(4)",
nullable: false,
oldClrType: typeof(string));

migrationBuilder.AlterColumn<string>(
name: "ProcessRatioId",
table: "MaterialCost",
type: "char(4)",
nullable: true,
oldClrType: typeof(string),
oldNullable: true);

migrationBuilder.AddPrimaryKey(
name: "PK_ProcessRatio",
table: "ProcessRatio",
column: "ProcessRatioId");//添加主键


migrationBuilder.CreateIndex(
name: "IX_MaterialCost_ProcessRatioId",
table: "MaterialCost",
column: "ProcessRatioId");//添加索引

migrationBuilder.AddForeignKey(
name: "FK_MaterialCost_ProcessRatio_ProcessRatioId",
table: "MaterialCost",
column: "ProcessRatioId",
principalTable: "ProcessRatio",
principalColumn: "ProcessRatioId",
onDelete: ReferentialAction.Restrict);//添加外键
}

posted @ 2022-03-14 16:03  混子程序员ZMY  阅读(615)  评论(0编辑  收藏  举报