2012-07-30 110 views
5

我無法使級聯刪除正常工作。這是我的外鍵表:代碼優先級中的外鍵級聯刪除

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 
} 

有三種不同的方式我嘗試過。當我不使用任何流暢的API時,它會適當地設置表和外鍵,但級聯刪除不起作用。當我使用此代碼:

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

它創建了一個第二列,所以我有一個完全空MedicalPlan_Id然後,它填補了MedicalPlan_Id1。當我使用這個:

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

我得到一個錯誤創建數據庫。我怎樣才能正確設置級聯刪除?

回答

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

...應該是正確的映射。如果省略Withoptional(...)中的lambda表達式,則EF假定MedicalPlan.CoverageLevelsCoverageLevel實體中沒有逆導航屬性,並且CoverageLevel.MedicalPlan屬於另一個關係,即第二個外鍵的原因。