简体   繁体   中英

Entity Framework POCO - Possible to set Cascade?

I have your basic recursive categories that are linked between each other. When I try to delete a category that has children I get your usual error.

What I always did is made a functions to recursively delete all children but I wonder can I just somehow set CASCADE ON DELETE somehow to my POCO class that is using EF so I would not need implement my own deletion mechanics?

Error

The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.Categories_dbo.Categories_RootCategoryId". The conflict occurred in database "Website", table "dbo.Categories", column 'RootCategoryId'.

Model

public class Category
{
    public int Id { get; set; }

    public int? RootCategoryId { get; set; }
    public virtual Category RootCategory { get; set; }
    public virtual ICollection<Category> ChildCategories { get; set; }
}

What I have now

Currently I delete relation before deleting a category. But what if I want to delete all child-categories recursively? Only cascading them will accomplish that.

public ActionResult Delete(int id)
{
    var category = _db.Categories.Single(x => x.Id == id);
    if (category.RootCategoryId == null)
    {
        category.ChildCategories.ToList().ForEach(x => x.RootCategoryId = null);
    }
    else
    {
        category.ChildCategories.ToList().ForEach(x => x.RootCategoryId = category.RootCategoryId);
    }
    _db.Categories.Remove(category);
    _db.SaveChanges();
    return RedirectToAction("Index", "Category");
}

The way I would approach this issue would be to use the OnModelCreating Fluent api.

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
    modelBuilder.Entity()
        .HasMany(u => u.ProjectAuthorizations)
        .WithRequired(a => a.UserProfile)
        .WillCascadeOnDelete(true);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM