Cascading foreign key deletion in Code First

I cannot get cascading deletes to work correctly. This is my external key table:

public class CoverageLevel
{
    public int Id { get; set; }
    public virtual MedicalPlan MedicalPlan { get; set; }  //foreign key
    public virtual VisionPlan VisionPlan { get; set; }    //foreign key
    public virtual DentalPlan DentalPlan { get; set; }    //foreign key
}

There are three different ways I've tried. When I do not use any free API, it sets tables and foreign keys correctly, but cascading deletion does not work. When I use this code:

modelBuilder.Entity<MedicalPlan>().HasMany(t => t.CoverageLevels).WithOptional.WillCascadeOnDelete();

it creates a second column, so I'm completely null MedicalPlan_Id, and then MedicalPlan_Id1it fills. When I use this:

modelBuilder.Entity<MedicalPlan>().HasMany(t => t.CoverageLevels).WithOptional().HasForeignKey(d => d.MedicalPlan).WillCascadeOnDelete();

I get an error creating a database. How to configure cascading deletion?

+5
source share
1 answer
modelBuilder.Entity<MedicalPlan>()
    .HasMany(m => m.CoverageLevels)
    .WithOptional(c => c.MedicalPlan)
    .WillCascadeOnDelete();

... . - Withoptional(...), EF , MedicalPlan.CoverageLevels CoverageLevel CoverageLevel.MedicalPlan , .

+4

All Articles