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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With