How to soft delete one to many relationships in EF core?

entity-framework entity-framework-6 entity-framework-core

Question

Let's say that I have a Category and Product entity with one to many relationship and when I delete Category I want to delete all products that belong to the category. And by deleting I mean setting IsDeleted flag to true since I don't want to delete it for real (which I could by specifying on delete cascade). I found out the way to set IsDeleted to true when Category is deleted however I can't figure out how to find products of that category and do the same thing for them. Any help?

    public override int SaveChanges()
    {
        ChangeTracker.DetectChanges();

        foreach(var item in ChangeTracker.Entries<Category>().Where(e => e.State == EntityState.Deleted))
        {      
            item.State = EntityState.Modified;
            item.CurrentValues["IsDeleted"] = true;
        }

        return base.SaveChanges();
    }

I also specified query filter so that I don't get deleted items

    builder.Entity<Category>().Property<bool>("IsDeleted");
    builder.HasQueryFilter(c => !EF.Property<bool>(c, "IsDeleted"));
1
1
12/13/2017 10:26:00 PM

Popular Answer

Just use on cascade delete. When you delete category also all products of that category will be marked as deleted based on navigation property. This will be done by EFCore itself. I'm using this aproach in my code to soft delete one to many relation. Then use (so your code repeated on products):

public override int SaveChanges()
{
    ChangeTracker.DetectChanges();

    foreach(var item in ChangeTracker.Entries<Category>().Where(e => e.State 
     == EntityState.Deleted))
    {      
        item.State = EntityState.Modified;
        item.CurrentValues["IsDeleted"] = true;
    }

    foreach(var item in ChangeTracker.Entries<Product>().Where(e => e.State 
     == EntityState.Deleted))
    {      
        item.State = EntityState.Modified;
        item.CurrentValues["IsDeleted"] = true;
    }

    return base.SaveChanges();
}
0
12/15/2017 1:10:51 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow