Entity Framework 5 Soft Delete

北战南征 提交于 2019-12-14 03:57:55

问题


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


回答1:


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.




回答2:


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();
    }


来源:https://stackoverflow.com/questions/25993310/entity-framework-5-soft-delete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!