在表'Posts‘上引入外键约束'FK_Posts_Posts_RepostId’可能会导致循环或多个级联路径。指定“删除不操作”或“更新不操作”,或修改其他外键约束。
尝试1
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
public int? RepostId { get; set; }
public Post Repost { get; set; }
}Fluent API
builder.Entity<Post>()
.HasOne(s => s.Repost)
.WithOne()
.OnDelete(DeleteBehavior.SetNull);企图2
https://stackoverflow.com/a/53678583/13434418
public class Repost
{
public Repost()
{
Posts = new HashSet<Post>();
}
public int Id { get; set; }
public int? PostId { get; set; }
public virtual Post? Post { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}public class Post
{
public int Id { get; set; }
public string Text { get; set; } = null!;
public int? RepostId { get; set; }
public virtual Repost? Repost { get; set; }
public virtual Repost? RepostNavigation { get; set; }
}Fluent API
builder.Entity<Post>(entity =>
{
entity.HasOne(d => d.Repost)
.WithMany(p => p.Posts)
.HasForeignKey(d => d.RepostId)
.OnDelete(DeleteBehavior.SetNull)
.HasConstraintName("FK_Posts_Posts");
});
builder.Entity<Repost>(entity =>
{
entity.ToTable("Repost");
entity.HasIndex(e => e.PostId, "IX_Repost_PostId")
.IsUnique();
entity.HasOne(d => d.Post)
.WithOne(p => p.RepostNavigation)
.HasForeignKey<Repost>(d => d.PostId)
.OnDelete(DeleteBehavior.Cascade);
});删除post时,需要在repost中设置null。我可以使用DeleteBehavior.NoAction,但问题是,有什么方法可以在删除帖子时自动设置它吗?
UPD
解决方案
public class Post
{
public int Id { get; set; }
public string Text { get; set; }
public int? RepostId { get; set; }
public Post Repost { get; set; }
public ICollection<Post> Reposts { get; set; }
} builder.Entity<Post>()
.HasOne(s => s.Repost)
.WithMany(s => s.Reposts)
.HasForeignKey(s => s.RepostId)
.IsRequired(false)
.OnDelete(DeleteBehavior.ClientSetNull);发布于 2022-04-25 22:25:10
您的第一次尝试是接近的,只是使用自引用,或者任何属性名称与类型名称不同的引用,都需要显式配置FK:
这应该是可行的:
builder.Entity<Post>()
.HasOne(s => s.Repost)
.WithOne()
.HasForeignKey<Post>(s => s.RepostId)
.OnDelete(DeleteBehavior.ClientSetNull);DeleteBehavior.SetNull不是有效的选项,因为Server无法解决自引用FK上的该行为。如果尝试使用ON DELETE SET NULL在Server中设置自引用FK,则会得到相同的错误。通过使用ClientSetNull,EF可以在删除记录之前为任何相关实体发出UPDATE语句。
在删除相关实体时,如果SetNull碰巧跟踪了相关实体(Ies),那么DbContext可能会工作。
https://stackoverflow.com/questions/72005597
复制相似问题