• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
混子程序员
博客园    首页    新随笔    联系   管理    订阅  订阅
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 on 2022-03-14 16:03  混子程序员ZMY  阅读(725)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3