同一张表一比多的删除级联

问题描述 投票:0回答:1

在我的.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() in context:

        protected override void OnModelCreating(ModelBuilder builder) {
            builder.Entity<Comment>()
                .HasOne(c => c.Parent)
                .WithMany("Comments")
                .HasForeignKey("ParentId")
                .OnDelete(DeleteBehavior.Cascade);
            base.OnModelCreating(builder);
        }
c# entity-framework asp.net-core one-to-many
1个回答
0
投票

不需要手动处理。你可以在OnModelCreating里面添加Cascade Behavior到你的实体中,如下所示。

foreach (var foreignKey in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            {
                foreignKey.DeleteBehavior = DeleteBehavior.Cascade;
            }

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.