簡體   English   中英

刪除級聯上的同一個表一對多

[英]Same table one to many on delete cascade

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

評論.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);
        }

無需手動處理。 您可以將級聯行為添加到您的實體,如下所示。 在 OnModelCreating 里面;

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM