可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束相关的知识,希望对你有一定的参考价值。

实体框架核心

在执行update-database时抛出错误

错误: - 在表'UserRoleRelationship'上引入FOREIGN KEY约束'FK_UserRoleRelationship_UserRoels_ParentUserRoleId'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束或索引。

public class UserRoleRelationship 
{
    [Key]
    public int Id { get; set; }
    [Required]
    public Guid UserRoleRelationshipId { get; set; }

    public virtual UserRole ChildUserRole { get; set; }
    public int ChildUserRoleId { get; set; }

    public virtual UserRole ParentUserRole { get; set; }
    public int ParentUserRoleId { get; set; }

}

public class UserRole 
{
    [Key]
    public int Id { get; set; }
    [Required]
    public Guid UserRoleId { get; set; }
    public virtual Role Role { set; get; }
    public int RoleId { set; get; }
    public virtual U.User User { set; get; }
    public int UserId { set; get; }
}
答案

对于您当前的模型设计,它将在下面创建迁移:

            migrationBuilder.AddForeignKey(
            name: "FK_UserRoleRelationship_UserRole_ChildUserRoleId",
            table: "UserRoleRelationship",
            column: "ChildUserRoleId",
            principalTable: "UserRole",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

        migrationBuilder.AddForeignKey(
            name: "FK_UserRoleRelationship_UserRole_ParentUserRoleId",
            table: "UserRoleRelationship",
            column: "ParentUserRoleId",
            principalTable: "UserRole",
            principalColumn: "Id",
            onDelete: ReferentialAction.Cascade);

当删除FK_UserRoleRelationship_UserRole_ChildUserRoleId时,FK_UserRoleRelationship_UserRole_ParentUserRoleIdUserRole都将删除UserRoleRelationship中的记录,这将导致多个级联删除。

要解决此问题,请尝试将int设为int?,如下所示:

        public int? ParentUserRoleId { get; set; }

哪个会创造

migrationBuilder.AddForeignKey(
                name: "FK_UserRoleRelationship_UserRole_ParentUserRoleId",
                table: "UserRoleRelationship",
                column: "ParentUserRoleId",
                principalTable: "UserRole",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);

注意 您需要先删除UserRole,然后删除UserRoleRelationship

以上是关于可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束的主要内容,如果未能解决你的问题,请参考以下文章

FOREIGN KEY可能会导致循环或多个级联路径异常[重复]

OnDelete(DeleteBehavior.Cascade) 可能会导致循环或多个级联路径

错误:引入FOREIGN KEY约束可能会导致循环或多个级联路径

循环或多个级联路径。 SQL 错误?

Entity Framework Core 5 - 在表上引入 FOREIGN KEY 约束可能会导致循环或多个级联路径

在表“ReservedSeats”上引入 FOREIGN KEY 约束“FK_ReservedSeats_Seats_SeatId”可能会导致循环或多个级联路径