且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架:全局禁用删除

更新时间:2023-02-13 14:39:42

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

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

base.SaveChanges();
}

编辑



我阅读了关于 EF Core 的git:


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




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


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!

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