首页 > 解决方案 > 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!

标签: c#entity-frameworkentity-framework-core

解决方案


实际上 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); 

推荐阅读