Entity framework: disable delete globally

时间:2016-07-11 19:15:00

标签: asp.net entity-framework entity-framework-core

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!

3 个答案:

答案 0 :(得分:2)

角色选项是一种方式,但您也可以覆盖SaveChanges

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

    base.SaveChanges();
}

修改

我在git上读到EF Core

  

如果要更改所有关系的删除行为,那么   您可以在OnModelCreating(...)中使用此代码为所有人批量设置它   模型中的关系。

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

答案 1 :(得分:1)

威廉的答案几乎就是这样做的,但你也可以这样做。

设置Delete以抛出异常,并添加DeleteVirtual方法。主要是这也是更新,您可以通过更新validUntil字段进行所需的软删除。

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


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

答案 2 :(得分:1)

您可以在SaveChanges()课程中覆盖DbContext方法,然后您可以获取已删除实体的列表,并将Status更改为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();
}