Entity Framework Core cascade delete one to many relationship

前端 未结 2 1276
灰色年华
灰色年华 2020-12-15 22:01
public class Station : IEntitie
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection         


        
相关标签:
2条回答
  • 2020-12-15 22:46

    Described "problem" is not related to Entity Framework - this is restriction of MS SQL Server itself. Table with several FKs may have only one of them with cascade delete.

    So, as soon as you need both FKs to have cascade - you should implement such "cleanup" in your code. Set one (or both) FKs to DeleteBehavior.Restrict, and in your controller/service prior to removing Station manually find and delete all related RegulatorySchedule

    0 讨论(0)
  • 2020-12-15 22:56

    Dmitry's answer worked perfectly. For any future traveler a working sample of a mapping table down below.

    The code is located in the OnModelCreating(ModelBuilder modelBuilder) method in your DbContext class:

    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
    
    0 讨论(0)
提交回复
热议问题