How to set on delete cascade for self reference Foreign Key in Entity Framework in ASP.NET

自古美人都是妖i 提交于 2019-12-11 19:28:42

问题


I am developing an ASP.NET MVC project. I am using Entity Framework code first approach to interact with database. But I am having a problem with setting on cascade delete for self-reference foreign key for an entity.

This is my entity class with self reference foreign key

public class Category
    {
        public int Id { get; set; }
        [Required]
        [MaxLength(50)]
        public string Name { get; set; }
        [MaxLength(55)]
        public string MmName { get; set; }
        public int? ParentId { get; set; }

        [ForeignKey("ParentId")]
        public virtual Category ParentCategory { get; set; }
        public virtual ICollection<Category> Categories { get; set; }
    }

This is my context

public class StoreContext : DbContext
    {
        public StoreContext():base("DefaultConnection")
        {

        }

        public DbSet<Category> Categories { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>().HasOptional(x => x.ParentCategory).WithMany(c => c.Categories).WillCascadeOnDelete();
        }
    }

When I run, multiple cascade path errors throw

Introducing FOREIGN KEY constraint 'FK_dbo.Categories_dbo.Categories_ParentId' on table 'Categories' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.

Is it possible set on delete cascade for self-referencing foreign key in entity framework code first?


回答1:


i also faced the similar issue, and if i remember correctly what i found is EF doesn't support cassade delete on self reference, so we need to handle it by code. What i followed is

  • Remove the cascade delete from fluent api or generated migration.
  • Add code to delte/setnull all self-reference and then delete.


来源:https://stackoverflow.com/questions/37936221/how-to-set-on-delete-cascade-for-self-reference-foreign-key-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!