gpt4 book ai didi

c# - 在不删除数据的情况下重命名 Entity Framework Core 中的外键

转载 作者:太空狗 更新时间:2023-10-29 22:15:30 25 4
gpt4 key购买 nike

我有两个模型类:

public class Survey
{
public int SurveyId { get; set; }
public string Name { get; set; }
}

public class User
{
public int UserId { get; set; }

public int SurveyId { get; set; }
public Survey Survey { get; set; }
}

我想将 Survey 重命名为 StudentSurvey,这样它将具有 StudentSurveyId。我相应地更新了模型中的类名和属性,并添加了一个迁移。

但是,我得到:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_User_Surveys_SurveyId". The conflict occurred in database "AppName", table "dbo.Survey", column 'SurveyId'.

我认为它正在尝试删除数据,因为它需要列中的数据(不能为空),所以我看到了该错误。但我不想删除数据。我怎样才能重命名它?

最佳答案

EF Core 将实体类重命名视为删除旧实体并添加新实体,因此生成迁移以删除原始表并创建新表。

解决方法需要执行以下步骤:

(1) 在重命名实体之前,使用 ToTableHasColumnName 流畅的 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; }

你就完成了。

您可以通过添加新的迁移来验证这一点 - 它将具有空的 UpDown 方法。

关于c# - 在不删除数据的情况下重命名 Entity Framework Core 中的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49799627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com