在我的.NET Core应用程序中,我有一个评论系统,您可以在其中回复评论,也可以回复那些回复。答复和评论均为Comment
类型。我希望在删除父级时删除所有子级答复。但是我不知道如何配置它。
这是我上次迁移的外观,应该在删除级联上进行设置:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Comments_Comments_ParentId",
table: "Comments");
migrationBuilder.AddForeignKey(
name: "FK_Comments_Comments_ParentId",
table: "Comments",
column: "ParentId",
principalTable: "Comments",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
运行此迁移将引发:
Introducing FOREIGN KEY constraint 'FK_Comments_Comments_ParentId' on table 'Comments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
Comment.cs:
public class Comment {
public int Id { get; set; }
public string Text { get; set; }
public int MemeId { get; set; }
public string UserId { get; set; }
public ICollection<Comment> Comments { get; set; } = new HashSet<Comment>();
public Comment Parent { get; set; }
}
OnModelCreation()
中的上下文:
protected override void OnModelCreating(ModelBuilder builder) {
builder.Entity<Comment>()
.HasOne(c => c.Parent)
.WithMany("Comments")
.HasForeignKey("ParentId")
.OnDelete(DeleteBehavior.Cascade);
base.OnModelCreating(builder);
}