使用 EF Core 级联删除 [英] Cascade deleting with EF Core
问题描述
我目前在使用 EF Core 时遇到了一些问题.我有一些数据需要删除,我正在努力查看 fluent API 是如何工作的,完全与 .OnDelete()
函数有关.
I am having a few issues with EF Core at the moment. I have some data that I need to delete, and I am struggeling to see how the fluent API works, exactly in regards to the .OnDelete()
function.
考虑来自微软自己的网站,我想知道什么实体,正是 OnDelete()
是定位"(因为没有更好的词)在某些情况下,它似乎是博客,而在其他情况下,则是帖子.如果是这样,我想代码应该是这样的:
Considering the classic blog/post scenario from microsofts own websites, I wonder what entity, exactly the OnDelete()
is 'targeting' (for the lack of a better word) In some instances it seems to be the blog, in others, the post. Can the Cascade delete be defined from both sides (that the posts are deleted when the parent Blog is) if so i imagine the code should look like this:
model.Entity
据我所知,这是说删除博客后,首先删除所有引用此博客的帖子",这意味着 OnDelete(DeleteBehavior.Cascade)
适用于博客,而不是发布.
As i understand this is saying "When a Blog is deleted, first delete all posts referencing this blog" meaning the OnDelete(DeleteBehavior.Cascade)
applies to blog, not to post.
但这是一样的吗?
model.Entity
还是 OnDelete(DeleteBehavior.Cascade)
适用于 Post 而不是博客?
or does OnDelete(DeleteBehavior.Cascade)
apply to Post rather than blog?
推荐答案
级联删除总是在一个方向上起作用——从主体实体到依赖实体,即删除主体entity 删除依赖实体.对于一对多的关系,one 端总是 principal 而 many 端是 dependent.
Cascade delete always works in one direction - from principal entity to dependent entity, i.e. deleting the principal entity deletes the dependent entities. And for one-to- many relationships the one side is always the principal and the many side is the dependent.
看起来你对流畅的配置感到困惑.请注意,每个关系都由两端组成.流畅的配置允许您从一端开始并将其与另一端相关联,反之亦然,但您仍然在配置(定义)单一关系.所以
Looks like you are confused by the fluent configuration. Note that each relationship consists of two ends. The fluent configuration allows you to start with one of the ends and relate it to the other end, or vice versa, but still you are configuring (defining) a single relationship. So
Entity<A>().HasOne(a => a.B).WithMany(b => b.As)
与
Entity<B>().HasMany(b => b.As).WithOne(a => a.B);
并且它们都定义了一种相同的关系.您选择哪一个并不重要,只需为每个关系使用单一配置以避免差异.
and they both define one and the same relationship. Which one you choose doesn't matter, just use single configuration per relationship in order to avoid discrepancies.
话虽如此,
model.Entity<Post>().HasOne(p => p.Blog).WithMany(b => b.Posts)
.HasForeignKey(p => p.BlogId)
.OnDelete(DeleteBehavior.Cascade);
和
model.Entity<Blog>().HasMany(b => b.Posts).WithOne(p => p.Blog)
.HasForeignKey(p => p.BlogId)
.OnDelete(DeleteBehavior.Cascade);
是一回事,定义了从Blog
到Post
的单一一对多关系.由于Blog
是one 方面而Post
是many 方面,Blog
是主体实体,Post
是依赖实体,因此删除一个Blog
将删除相关的发布
s.
is one and the same and define single one-to-many relationship from Blog
to Post
. Since Blog
is the one side and Post
is the many side, the Blog
is the principal entity and the Post
is the dependent entity, hence deleting a Blog
will delete the related Post
s.
参考:
这篇关于使用 EF Core 级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!