fluent API on table 与自身有关系

fluent API on table that has relation with itself

我创建了一个与自身有关系的 table table 有一个一对多的关系,这里是我的实体:

    public class Permission
    {
        [Key]
        public int PermissionId { get; set; }      
        public string PermissionTitle { get; set; }
        public int? ParentId { get; set; }

        #region Relations

        [ForeignKey("ParentId")]
        public virtual ICollection<Permission> Permissions { get; set; }   

        #endregion

    }

但是当我使用迁移在 SQL 中创建 table 时,update-database 因以下错误而失败:

Introducing FOREIGN KEY constraint 'FK_Permission_Permission_ParentId' on table 'Permission' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

所以我决定使用 fluent API 来解决这个问题,但我不知道如何通过 Fluent API 在 table 上指定 ON DELETE NO ACTION与自身的关系。有帮助吗? 有什么办法可以解决我的问题吗?

对于 EF Core,实体通常应该有两个导航属性,如下所示:

public class Permission
{
    [Key]
    public int PermissionId { get; set; }
    public string PermissionTitle { get; set; }
    public int? ParentPermissionId { get; set; }

    #region Relationships
    public virtual Permission ParentPermission { get; set; }

    public virtual ICollection<Permission> ChildPermissions { get; } = new HashSet<Permission>();
    #endregion

}

配置如下:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Permission>()
            .HasMany(p => p.ChildPermissions)
            .WithOne(p => p.ParentPermission)
            .HasForeignKey(p => p.ParentPermissionId)
            .OnDelete(DeleteBehavior.Restrict);

        base.OnModelCreating(modelBuilder);
    }