c# - Entity Framework (Core) - cascading delete
问题描述
I’m using EF Core 3.1.1, but I believe this question applies to all versions of EF.
It seems the EF has the ability to cascade delete - if it is enabled, and if the dependent objects are loaded in the context.
var blog = context.blogs.Include(x => x.Posts).First(x => x.BlogId == id);
context.blogs.Remove(blog);
The above statement deletes all the blog’s posts, and then the blog - each with a different sql statement.
This is what I want, however when using code-first, it also creates the tables with cascading delete enabled in the database. (ON DELETE CASCADE
)
Can you enable cascade delete in EF, and rely of EF deleting dependent objects, without also enabling database level cascade delete? (Or am I understanding this incorrectly?)
The reason is migrations fail because SQL won’t enable cascade delete in the database because it detects multiple cascade paths (even though multiple wouldn’t occur naturally in the schema)
Thanks!
解决方案
实际上 EF Core 3.0 是 EF 的第一个版本,它通过DeleteBehavior.ClientCascade选项添加了此类功能(遗憾的是尚未包含在文档的Cascade Delete部分中):
对于被 跟踪的
DbContext
实体,相关主体被删除时,依赖实体将被删除。如果数据库是使用实体框架迁移或
EnsureCreated()
方法从模型创建的,那么如果违反外键约束,数据库中的行为将生成错误。
很快,所有Client*
删除行为都映射到Restrict
,即在数据库中强制执行 FK 关系,没有级联。客户端行为仅适用于上下文跟踪的实体,因此请确保Include
在删除之前确保相关数据(如您的示例中所示)。
要配置该选项,您至少需要具有有效Has
+With
的 fluent API 才能访问OnDelete
方法,例如
modelBuilder.Entity<Blog>()
.HasMany(e => e.Posts)
.WithOne(e => e.Blog)
.OnDelete(DeleteBehavior.ClientCascade);
推荐阅读
- eclipse-cdt - 液晶显示旧数据和新数据
- facebook-graph-api - 在没有 manage_pages 权限的情况下从 facebook graph API 获取 instagram ID
- reactjs - Meteor 方法如何返回结果?
- angular - 获取 API 响应中的特定对象
- firefox - 如何在 Robot Framework 上打开 Firefox 53
- plugins - Shopify 中使用的插件是什么?
- python - python - 如何将列设置为DataFrame中的索引
- node.js - 如何在信使欢迎屏幕上添加按钮?
- django - Django websockets 身份验证
- android - 为什么我对一个包中的代码所做的更改没有反映在实际的应用程序中?