Entity Framework Core cascade delete one to many relationship

前端 未结 2 1284
灰色年华
灰色年华 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: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()
                .HasKey(e => new { e.AId, e.BId});
    
    modelBuilder.Entity()
                .HasOne(e => e.A)
                .WithMany(e => e.ABs)
                .HasForeignKey(e => e.AId)
                .OnDelete(DeleteBehavior.Cascade); // <= This entity has cascading behaviour on deletion
    
    modelBuilder.Entity()
                .HasOne(e => e.B)
                .WithMany(e => e.ABs)
                .HasForeignKey(e => e.BId)
                .OnDelete(DeleteBehavior.Restrict); // <= This entity has restricted behaviour on deletion
    

提交回复
热议问题