Entity framework: disable delete globally

我们两清 提交于 2020-01-04 07:47:13

问题


We are starting a new application. We want to use Entity Framework. We are little afraid of deleting sql rows accidentally (especially by set related data accidentally etc.)

I thought to disable every delete, since we just mark every row with "validUntil" column and never delete rows.

I saw that it can done by roles in sql, but I want that all logic and control will be just in code.

Maybe in Entity Framework core there is new feature to enable that? I know that it can still write row sql with EF, but we don't afraid of such case.

I also tried remove setters of entities relationships to be more relax, but it broke the normal functionality of EF, and did not look like a good idea.

I saw in the above link a recommendation to use the Repository Pattern, but here it looks like it is not good practice.

How can I work safely with EF? thanks!


回答1:


The role option is one way, but you can also override SaveChanges.

public override int SaveChanges()
{
    foreach (DbEntityEntry entity in this.ChangeTracker.Entries)
    {
        if (entity.State == System.Data.EntityState.Deleted)
            return;        
    }

    base.SaveChanges();
}

EDIT

I read on git that for EF Core:

If you want to change the delete behavior for all relationships, then you can use this code in OnModelCreating(...) to bulk set it for all relationships in your model.

foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
    relationship.DeleteBehavior = DeleteBehavior.Restrict;
}



回答2:


William's answer is pretty much the way to do it, but you can also do something like this.

Set the Delete to throw an exception, and add a DeleteVirtual method. Primarily this is also update, where you can do the soft delete you want via updating the validUntil field.

    T IDbContext.Delete<T>(T entity)
    {
         throw new NotImplementedException();
    }


    T IDbContext.DeleteVirtual<T>(T entity)
    {
        this.Entry(entity).State = EntityState.Modified;
        return entity;
    }



回答3:


You can override SaveChanges() method in DbContext class and in there you can get a list of deleted entities and change their Status to Unchanged.

public override int SaveChanges()
{
    var DeletedEntities = ChangeTracker.Entries().Where(E => E.State == EntityState.Deleted).ToList();

    DeletedEntities.ForEach(E => 
    {
        E.State = EntityState.Unchanged;
    });

    return base.SaveChanges();
}


来源:https://stackoverflow.com/questions/38314487/entity-framework-disable-delete-globally

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