我使用实体框架核心解决方案跟踪.net核心2的简化模式:
1+--------+1
+-------+Blogs +-------+
| +--------+ |
*| |*
+--------+ +----------+
|Posts | |Tags |
+--------+ +----------+
|1 1|
| *+-------------+* |
+----+PostTags |------+
+-------------+
使用以下型号:
public class Blog
{
public int Id { get; set; }
public ICollection<Post> Posts { get; set; }
public ICollection<Post> Tags { get; set; }
}
public class Post
{
public int Id { get; set; }
public Blog Blog { get; set; }
public ICollection<PostTag> PostTags { get; set; }
}
public class Tag
{
public int Id { get; set; }
public Blog Blog { get; set; }
public ICollection<PostTag> PostTags { get; set; }
}
public class PostTag
{
public int PostId { get; set; }
public Post Post { get; set; }
public int TagId { get; set; }
public Tag Tag { get; set; }
}
和相应的DbContext:
public class DataDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<PostTag> PostTags { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostTag>()
.HasKey(u => new { pt.TagId, pt.PostId });
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Post)
.WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostId)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
modelBuilder.Entity<PostTag>()
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId)
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
}
级联删除工作,但留下Tags
与博客无效。如果我在Tag中的[Require]
博客,我收到一个循环约束错误。
我想我自己找到了答案:
“在SQL Server中,一个表不能在DELETE或UPDATE语句启动的所有级联引用操作的列表中出现多次。例如,级联引用操作树必须只有一个路径到级联引用动作树上的特定表
在EF Core中是否有一个优雅的解决方案,以确保在删除博客后立即删除所有标签和帖子?
在EF Core中是否有一个优雅的解决方案,以确保在删除博客后立即删除所有标签和帖子?
你有两个选择:
1)有帖子 - > PostTags级联删除和Blogs-> BlogTags级联删除,并先删除所有Blog的帖子,然后删除博客。
2)在博客上写一个INSTEAD OF DELETE触发器,删除相关的帖子和BlogTags,然后再删除博客。