2016-12-15 93 views
0

我有這個模型(簡體)相關的條目:實體框架中刪除,而不是設置爲null FK

public class Request 
{ 
    [Key] 
    public int Id { get; set; } 
    public virtual StructuredNote Response { get; set; } 
} 

而且每個StructuredNoteList<CallSchedComp>這樣的:

public class StructuredNote 
{ 
    public virtual List<CallSchedComp> CallSchedule { get; set; } 
} 

我想更新特別是RequestCallSchedule。問題往往是我需要完全重新生成CallSchedule,而不是修改現有的參考CallSchedule。當再生一個全新的List<CallSchedComp>,明顯的指針現在是新的,因此,結束意外事件發生時,我做這樣的事情:

request.Response.CallSchedule = NewCallScheduleWithNewPointer; 
_ctxt.Entry(request).State = EntityState.Modified; 

是英孚設置的List<CallSchedule>null代替現有CallSchedComp S部的FKS從數據庫中刪除它們。新的CallSchedComp有正確的FK指向Response。我相信這是默認的EF行爲,對嗎?

我的問題:

  1. 有沒有一種方法,以消除在數據庫中的舊List<CallSchedComp>,而不是僅僅設置了外鍵爲空?
  2. 如果不影響性能,我是否應該對此感到困擾?

希望它很清楚。謝謝!

編輯:由於每個請求:

public class CallSchedComp 
{ 
    [Key] 
    public int CallSchedCompId { get; set; } 

    [Range(typeof(DateTime), "1/1/1900", "6/6/2079")] 
    public DateTime ObservationDate { get; set; } 

    [Range(typeof(DateTime), "1/1/1900", "6/6/2079")] 
    public DateTime PaymentDate { get; set; } 
    public decimal Coupon { get; set; } 
    public decimal Strike { get; set; } 
    public OptionType OptionType { get; set; } 
    public CallType CallType { get; set; } 
    public decimal CallPrice { get; set; } 
    public decimal AutoCallLevel { get; set; } 
    public decimal UpsideStrike { get; set; } 
    public decimal UpsideParticipation { get; set; } 
    public bool ExcessParticipationOnAutoCallOnly { get; set; } 

    public virtual StructuredNote IncomeNote { get; set; } 

    [Timestamp] 
    public byte[] Timestamp { get; set; } 
} 

而且非常基本fluentAPI配置。我幾乎完全使用註釋來配置關係。

 modelBuilder.Entity<CallSchedComp>().Property(x => x.AutoCallLevel).HasPrecision(18, 4); 
     modelBuilder.Entity<CallSchedComp>().Property(x => x.CallPrice).HasPrecision(18, 4); 
     modelBuilder.Entity<CallSchedComp>().Property(x => x.Coupon).HasPrecision(18, 4); 
     modelBuilder.Entity<CallSchedComp>().Property(x => x.Strike).HasPrecision(18, 4); 
     modelBuilder.Entity<CallSchedComp>().Property(x => x.UpsideParticipation).HasPrecision(18, 4); 
     modelBuilder.Entity<CallSchedComp>().Property(x => x.UpsideStrike).HasPrecision(18, 4); 
+0

這取決於關係的配置方式。你能否顯示CallSchedule模型(具有PK,FK /導航,數據註釋和/或流暢配置等所有基本屬性)? –

回答

1

這是這種情況。在CallSchedComp類中,您只有導航屬性IncomeNote,但沒有明確的FK屬性,沒有數據註釋,也沒有流暢的關係配置。因此,按照慣例,關係的許多方面是可選的(可爲空的FK)和級聯行爲,EF處理您描述的方式 - 通過將FK列設置爲null

只有這樣,才能讓EF級聯刪除相關記錄中,使IncomeNote要求:

modelBuilder.Entity<CallSchedComp>() 
    .HasRequired(e => e.IncomeNote) 
    .WithMany(e => e.CallSchedule) 
    .WillCascadeOnDelete(); 
+0

謝謝伊萬。所以,如果我讓我的FK顯式和必需,我的默認行爲是級聯刪除? – coolboyjules

+0

是的。您必須將其設置爲不可空字段,並將其與'ForeignKey'屬性關聯到導航屬性,並且它將成爲必需/級聯刪除。 –

+0

很好,我會給你一個鏡頭。再次感謝。只是好奇,我沒有指定一個明確的FK,但在DB中仍然有一個FK。我猜EF如果有導航屬性就知道創建一個選項FK? – coolboyjules