1. 程式人生 > 其它 >ef core修改主鍵型別相關刪除外來鍵索引約束以及重建過程

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);//新增外來鍵
}