Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DbModelBuilder with Database First Approach to implement Soft Delete

I'm trying to implement a soft delete in our EF 6 project. We are using the database first approach and I noticed that you cannot override OnModelCreating.

When using the Code-First approach it's possible to apply a global filter for a particular entity as described in this blog post.

How can I recreate this using the Database First approach?

public class MyContext : DbContext
{
    public virtual IDbSet<Company> Companies { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Company>()
            .Map(m => m.Requires("IsDeleted").HasValue(false))
            .Ignore(m => m.IsDeleted);
    }
}
like image 604
rd53hu Avatar asked Dec 20 '25 09:12

rd53hu


1 Answers

Best approach to standardize soft deleting entities, explained below step-by-step.

1- Create ISoftDelete interface:

public interface ISoftDelete
{
    bool IsDeleted { get; set; }
}

2- Then create your entities you want to implement soft-delete approach.

public class Company : ISoftDelete
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long CompanyId { get; set; }
    public string Name { get; set; }
    public bool IsDeleted { get; set; }
}

3- Change state of entity from "Deleted" to "Modified" by overriding DBContext.SaveChanges() method something like below.

public override int SaveChanges()
{
    foreach (var entry in ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted))
        TryCancelDeletion(entry);

    return base.SaveChanges();
}

private bool TryCancelDeletion(EntityEntry entry)
{
    if (!(entry.Entity is ISoftDelete))
        return false;

    entry.Reload();
    entry.State = EntityState.Modified;
    ((ISoftDelete)entry.Entity).IsDeleted = true;
    return true;
}

Soft-delete entities are not actually deleted, marked as IsDeleted = true in the database, but can not be retrieved to the application normally.

You should apply default filters for exclude soft-deleted entities from results.

like image 172
jepozdemir Avatar answered Dec 21 '25 22:12

jepozdemir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!