gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:11:46 24 4
gpt4 key购买 nike

Entity Framework 核心

执行更新数据库时抛出错误

错误:-
在表 '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两者都将删除 UserRole 中的记录删除时 UserRoleRelationship这将导致多个级联删除。

如需解决方法,请尝试制作 intint?像下面这样:
        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

关于entity-framework - ...可能会导致循环或多个级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52268985/

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