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

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

Question

Let's imagine I have a one-to-many link between a category and a product, and when I remove the category, I want to also delete all the items that are associated with it. And because I don't want to really delete it, I'm setting the IsDeleted flag to true instead (which I could by specifying on delete cascade). When a category is destroyed, I've figured out how to change IsDeleted to true, but I'm at a loss on how to locate the goods in that category and apply the same technique to 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();
    }

In order to avoid seeing deleted entries, I additionally provided a query filter.

    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

Use just for cascade deletion. Based on navigation characteristic, when you remove a category, all of its goods are likewise tagged as deleted. EFCore will take care of this on its own. This approach is what I'm using in my code to softly erase one-to-many relationships. So that your code is replicated on items, use:

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