简体   繁体   中英

Entity Framework 5 Soft Delete

I am trying to prevent any deletes on my database tables. Currently using Entity Framework 5. Firstly here is my code,

public override int SaveChanges()
    {
        var Changed = ChangeTracker.Entries();
        if (Changed != null)
        {
            foreach (var entry in Changed.Where(e => e.State == EntityState.Deleted))
            {
                entry.State = EntityState.Unchanged;
            }
        }

        return base.SaveChanges();
    }

I've managed to prevent it with this way. When i use Remove method of EF its not working anymore.However, what i am trying to achieve is, when i use the remove method for the given ID, i want to set isDeleted(which is a (bit) column in all my db tables) value to false. Currently, i am lost in the documents and shared codes around the internet.

Thanks

I would probably handle this by making entities that are soft deletable implement an interface, something like ISoftDeletable.

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

Then extend your code above to check if the entity type implements the ISoftDeletable interface, if it does simply set IsDeleted to true.

public override int SaveChanges()
    {
        var Changed = ChangeTracker.Entries();
        if (Changed != null)
        {
            foreach (var entry in Changed.Where(e => e.State == EntityState.Deleted))
            {
                entry.State = EntityState.Unchanged;
                if (entry.Entity is ISoftDeletable)
                {
                    // Set IsDeleted....
                }
            }
        }

        return base.SaveChanges();
    }

You would then need to make sure queries for the Entities that implement ISoftDeletable filter out those that are soft deleted.

Building on @BenjaminPauls great answer, but using the generic Entries<TEntity> . In my opinion it cleans up the code and the nestling a bit.

public override int SaveChanges()
{
    foreach (var entry in ChangeTracker.Entries<ISoftDeletable>())
    {
        if (entry.State == EntityState.Deleted)
        {
            // Set deleted.
        }
    }
    return base.SaveChanges();
}

Or even:

    public override int SaveChanges()
    {
        foreach (var entry in ChangeTracker.Entries<ISoftDeletable>()
            .Where(x => x.State == EntityState.Deleted)
        {
            // Set deleted.
        }
        return base.SaveChanges();
    }

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