實體框架核心級聯刪除一對多關係

c# entity-framework entity-framework-core

public class Station : IEntitie
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<RegulatorySchedule> RegulatoryScheduleDispatchStations { get; set; }    

    public virtual ICollection<RegulatorySchedule> RegulatoryScheduleDestinationStations { get; set; }   
}

public class RegulatorySchedule : IEntitie
{
    [Key]
    public int Id { get; set; }

    public virtual Station DispatchStation { get; set; }      

    public virtual Station DestinationStation { get; set; }     
}


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        modelBuilder.Entity<RegulatorySchedule>()
            .HasOne(s => s.DestinationStation)
            .WithMany(s => s.RegulatoryScheduleDestinationStations)
            .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);

        modelBuilder.Entity<RegulatorySchedule>()
            .HasOne(s => s.DispatchStation)
            .WithMany(s => s.RegulatoryScheduleDispatchStations)
            .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict);
}

僅當我在刪除Restrict OnDelete (Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict)時清楚地暴露行為時,才會在遷移期間創建數據庫。否則,它會拋出異常:

“在表'RegulatorySchedules'上引入FOREIGN KEY約束'FK_RegulatorySchedules_Stations_DispatchStationId'可能會導致循環或多個級​​聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。”

我需要刪除表格的站點站點以及與表格相關的屬性RegulatorySchedules DispatchStation和DestinationStation暴露於NULL。但是Restrict選項在刪除我無法放入的SetNull時會出現異常。告訴我怎麼樣?

一般承認的答案

描述的“問題”與實體框架無關 - 這是對MS SQL Server本身的限制。具有多個FK的表可能只有一個具有級聯刪除。

所以,只要你需要兩個FK都有級聯 - 你應該在你的代碼中實現這樣的“清理”。將一個(或兩個)FK設置為DeleteBehavior.Restrict ,並在刪除Station之前在控制器/服務中手動查找並刪除所有相關的RegulatorySchedule


熱門答案

德米特里的回答完美無缺。對於任何未來的旅行者,下面的映射表的工作樣本。

代碼位於DbContext類的OnModelCreating(ModelBuilder modelBuilder)方法中:

modelBuilder.Entity<AB>()
            .HasKey(e => new { e.AId, e.BId});

modelBuilder.Entity<AB>()
            .HasOne(e => e.A)
            .WithMany(e => e.ABs)
            .HasForeignKey(e => e.AId)
            .OnDelete(DeleteBehavior.Cascade); // <= This entity has cascading behaviour on deletion

modelBuilder.Entity<AB>()
            .HasOne(e => e.B)
            .WithMany(e => e.ABs)
            .HasForeignKey(e => e.BId)
            .OnDelete(DeleteBehavior.Restrict); // <= This entity has restricted behaviour on deletion


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因