实体框架更改Id类型

本文关键字:Id 类型 框架 实体 | 更新日期: 2023-09-27 18:10:56

我已经将Id属性的类型从Int更改为Guid,没有其他实体引用该Id,我已经手动从数据库中删除了该实体的所有记录,我生成的迁移类看起来像这样:

public override void Up()
{
    AlterColumn("dbo.RoutineExercises", "RoutineExerciseId", c => c.Guid(nullable: false));
}
public override void Down()
{
    AlterColumn("dbo.RoutineExercises", "RoutineExerciseId", c => c.Int(nullable: false, identity: true));
}

当我运行update-database命令时,我得到了这个错误:

对象PK_dbo。RoutineExercises'依赖于列'RoutineExerciseId'。

和我的FluentAPI配置看起来像这样:

 modelBuilder.Entity<RoutineExercise>().HasKey(r => r.RoutineExerciseId);
 modelBuilder.Entity<RoutineExercise>()
                .HasRequired(r => r.Exercise)
                .WithMany()
                .HasForeignKey(r => r.ExerciseId)
                .WillCascadeOnDelete(true);
            modelBuilder.Entity<RoutineExercise>()
                .HasRequired(r => r.Routine)
                .WithMany()
                .HasForeignKey(r => r.RoutineId)
                .WillCascadeOnDelete(true);

如何在不删除整个数据库的情况下修复这个问题?

实体框架更改Id类型

您可以尝试分阶段进行迁移-我不确定,但您的流畅配置导致基于您想要更改的字段创建主键,并且迁移向导无法考虑需要删除主键,将字段转换为guid,然后重新构建新的主键。

所以我的建议是做迁移婴儿步骤:1. 从routineexerciseid中删除haskey,并将其移动到另一个字段,或者创建一个新的组合键(如果需要主键)2. 移动主键后,您应该能够更改列3.最后恢复该列上的主键。

或者创建一个全新的列作为guid作为主键,删除旧列,然后在必要时根据需要重命名新列

我知道这是一个古老的问题,但以防其他人正在寻找这个答案,我自己刚刚发现了它。

修改前需要删除主键。

DropPrimaryKey("dbo。,new[] {"RoutineExerciseId"});

进行迁移重置比更改大量内容并可能弄乱数据库要容易得多。我建议你在开始之前先备份你的数据。

流程概述如下:

https://weblog.west-wind.com/posts/2016/jan/13/resetting-entity-framework-migrations-to-a-clean-slate