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

... may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints

Entity Framework核心

更新数据库时抛出错误

错误:- 在 table '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_ChildUserRoleIdFK_UserRoleRelationship_UserRole_ParentUserRoleId在删除UserRoleRelationship时都会删除UserRole中的记录,会造成多次级联删除。

对于解决方法,请尝试将 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

解决方法是,尝试将 int 设为 int?,如下所示:

public int? ParentUserRoleId { get; set; }