Entity Framework Cascade Deletes One-To-Many Relationships

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);
}

The database is created during the migration only when I clearly show the deletion behavior Restrict OnDelete (Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Restrict). Otherwise, this throws an exception:

"Representation of the FOREIGN KEY constraint 'FK_RegulatorySchedules_Stations_DispatchStationId' in the RegulatorySchedules table may cause loops or multiple cascading paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION or change other FOREIGN KEY."

I need to remove the Station stations of the table and the table-related properties of the RegulatorySchedules DispatchStation and DestinationStation that are displayed in NULL. But the Restrict parameter is an exception when you delete SetNull, which I cannot put. Tell me how to be?

+4
1

"" Entity Framework - MS SQL Server. FK .

, , FK , ​​ "" . ( ) FK DeleteBehavior.Restrict, / Station RegulatorySchedule

+5

Source: https://habr.com/ru/post/1667096/


All Articles