1
votes

I've created a table that has a relation with itself the table has a one-to-many relationship here is my Entity:

    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

    }

but when I used migration to create the table in SQL, update-database failed for this error:

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.

So I decided to use fluent API to solve this issue but I don't know how to Specify ON DELETE NO ACTION by Fluent API on a table that has a relation with itself. any help? is there any solution to solve my problem?

1

1 Answers

0
votes

For EF Core the Entity should normally have two Navigation Properties, like this:

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

}

And configured like this:

    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);
    }