实体框架:全局禁用删除 [英] Entity framework: disable delete globally
问题描述
我以为禁用每个删除,因为我们只是标记每一行validUntil 列,永远不会删除行。
我看到它可以通过角色完成在sql 中,但是我希望所有的逻辑和控件都将在代码中。
可能在Entity Framework核心中有新的功能来实现?我知道它仍然可以用EF写入行sql,但是我们并不害怕这种情况。
我还试图删除实体关系的setter来更放松,但是它打破了EF的正常功能,并不是一个好主意。
我在上面的链接中看到了一个使用存储库模式的建议,但是这里看起来好像不好。
与EF安全工作?
谢谢!
角色选项是一种方式,但您也可以覆盖 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;
}
这篇关于实体框架:全局禁用删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!