Entity framework: disable delete globally

asp.net entity-framework entity-framework-core

Question

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
2
5/23/2017 12:17:29 PM

Popular Answer

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
7/14/2016 8:23:50 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow