2016-12-15 52 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