EF Core 将实体类重命名视为删除旧实体并添加新实体,因此会生成迁移以删除原始表并创建新表。
解决方法需要以下步骤:
(1) 在重命名实体之前,使用ToTable 和HasColumnName fluent API 或数据注释“重命名”表和PK 列。也对引用实体的 FK 列执行相同的操作。
例如:
[Table("StudentSurveys")]
public class Survey
{
[Column("StudentSurveyId")]
public int SurveyId { get; set; }
public string Name { get; set; }
}
public class User
{
public int UserId { get; set; }
[Column("StudentSurveyId")]
public int SurveyId { get; set; }
public Survey Survey { get; set; }
}
(2) 添加新的迁移。它将正确地重命名表、PK 列、FK 列和相关的约束:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Users_Surveys_SurveyId",
table: "Users");
migrationBuilder.DropPrimaryKey(
name: "PK_Surveys",
table: "Surveys");
migrationBuilder.RenameTable(
name: "Surveys",
newName: "StudentSurveys");
migrationBuilder.RenameColumn(
name: "SurveyId",
table: "Users",
newName: "StudentSurveyId");
migrationBuilder.RenameIndex(
name: "IX_Users_SurveyId",
table: "Users",
newName: "IX_Users_StudentSurveyId");
migrationBuilder.RenameColumn(
name: "SurveyId",
table: "StudentSurveys",
newName: "StudentSurveyId");
migrationBuilder.AddPrimaryKey(
name: "PK_StudentSurveys",
table: "StudentSurveys",
column: "StudentSurveyId");
migrationBuilder.AddForeignKey(
name: "FK_Users_StudentSurveys_StudentSurveyId",
table: "Users",
column: "StudentSurveyId",
principalTable: "StudentSurveys",
principalColumn: "StudentSurveyId",
onDelete: ReferentialAction.Cascade);
}
(3) 移除注解/流利的配置并做实际的类/属性重命名:
public class StudentSurvey
{
public int StudentSurveyId { get; set; }
public string Name { get; set; }
}
public class User
{
public int SurveyUserId { get; set; }
public int StudentSurveyId { get; set; }
public StudentSurvey StudentSurvey { get; set; }
}
重命名对应的DbSet(如果有):
public DbSet<StudentSurvey> StudentSurveys { get; set; }
你就完成了。
您可以通过添加新迁移来验证这一点 - 它将有空的 Up 和 Down 方法。