同一表一对多删除级联

时间:2019-08-29 13:33:58

标签: c# entity-framework asp.net-core one-to-many

在我的.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);
        }

1 个答案:

答案 0 :(得分:0)

无需手动处理。您可以如下所示将“级联行为”添加到您的实体。 在OnModelCreating内部;

@tf.function
def use_model(model, ...):
  ...
  outputs = model(...)
  ...

# Create the model
model = convnet(...)
# It's a good idea to initialize it too
model(<dummy input>)  # or model.build(...)

use_model(model, ...)

enter image description here