实体框架核心
在执行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_ParentUserRoleId
和UserRole
都将删除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