我有以下 EF4 Code First 课程:
[Serializable]
public class WOChangeLogHeader
{
[Key]
public int WOChangeLogHeaderId { get; set; }
public DateTime tadded { get; set; }
public virtual WorkOrderHeader WO { get; set; }
public int WorkOrderHeaderId { get; set; }
[MaxLength(50)]
public string chng_type { get; set; }
[MaxLength(50)]
public string chng_process { get; set; }
public int chng_by { get; set; }
public virtual ICollection<WOChangeLog> ChangeLogRecords {get;set;}
}
[Serializable]
public class WOChangeLog
{
[Key]
public int WOChangeLogId { get; set; }
public DateTime tadded { get; set; }
public virtual WOChangeLogHeader ChangeLogHeader { get; set; }
public int WOChangeLogHeaderId { get; set; }
[MaxLength(50)]
public string chng_field { get; set; }
public string old_value { get; set; }
public string new_value { get; set; }
}
并设置添加一个新的 WoChangeLogHeader,如下所示:
private void addWOChangeLogRecord(string chgField, string oldVal, string newVal, WorkOrderHeader wo)
{
WOChangeLog log = new WOChangeLog();
log.chng_field = chgField.Trim();
log.old_value = oldVal == null ? "-NULL VALUE-" : oldVal.Trim();
log.new_value = newVal == null ? "-NULL VALUE-" : newVal.Trim();
log.tadded = DateTime.Now;
if (CurrentWOChangeLogHeader == null)
{
CurrentWOChangeLogHeader = new WOChangeLogHeader();
CurrentWOChangeLogHeader.WO = wo;
CurrentWOChangeLogHeader.WorkOrderHeaderId = wo.WorkOrderHeaderId;
CurrentWOChangeLogHeader.chng_by = -2;
CurrentWOChangeLogHeader.chng_process = "WindowsService";
CurrentWOChangeLogHeader.chng_type = "Auto-Update";
CurrentWOChangeLogHeader.tadded = DateTime.Now;
}
CurrentWOChangeLogHeader.ChangeLogRecords.Add(log); // Error here
}
然而此时 ChangeLogRecords 导航属性为空,所以我得到一个空对象引用错误......
但是,如果我尝试添加 WOChangeLogHeader 而不添加任何子项,以便随后可以像这样引用它:
WOChangeLog log = new WOChangeLog();
log.chng_field = chgField.Trim();
log.old_value = oldVal == null ? "-NULL VALUE-" : oldVal.Trim();
log.new_value = newVal == null ? "-NULL VALUE-" : newVal.Trim();
log.tadded = DateTime.Now;
log.ChangeLogHeader = CurrentWOChangeLogHeader;
然后我收到以下错误?
操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。
当 ChangeLogRecords 为空时,它也不会让我在 Context 上保存更改...
如何在这样的一对多关系中添加一个新实体,它是父实体?
谢谢格雷格