EF4 Code First将具有虚拟导航属性null的实体添加到1到多个

时间:2010-11-15 15:18:55

标签: entity-framework virtual one-to-many savechanges ef-code-first

我有以下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的导航属性为null,因此我得到一个空对象引用错误...

但是如果我尝试添加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上的SaveChanges ...

如何在这样的1对多关系中添加作为父级的新实体?

由于 格雷格

1 个答案:

答案 0 :(得分:0)

问题可能在这里:

public virtual WOChangeLogHeader ChangeLogHeader { get; set; } 
public int WOChangeLogHeaderId { get; set; } 

这两行都引用了标题,但只需要第一行。

尝试删除第二行。