Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cascade delete on a foreign key in Code First

I am unable to get the cascade delete to work properly. This is my foreign 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 tried. When I don't use any fluent API, it sets up the tables and foreign keys appropriately, but cascade delete doesn't work. When I use this code:

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

it creates a second column, so I have a completely null MedicalPlan_Id and then a MedicalPlan_Id1 that it fills. When I use this:

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

I get an error creating the database. How can I set up cascade delete properly?

like image 914
proseidon Avatar asked Oct 07 '22 02:10

proseidon


1 Answers

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

...should be the correct mapping. If you omit the lambda expression in Withoptional(...) EF assumes that MedicalPlan.CoverageLevels has no inverse navigation property in the CoverageLevel entity and that CoverageLevel.MedicalPlan belongs to another relationship which is the reason for the second foreign key.

like image 92
Slauma Avatar answered Oct 26 '22 23:10

Slauma