新的外部实体不是使用Update创建的

时间:2015-06-12 19:11:24

标签: c# entity-framework

当我将新项目添加到我的实体的虚拟集合属性时,它将被添加到数据库中。

例如

Loan.Notes.Add(new Note {Subject = "Test"})

这将在Notes表中创建一个新行,并显示该链接的loanId。

我试图为另一个表复制这个确切的工作功能。我在点击保存之前设置了断点,我可以看到该集合具有NEW实体,但它不会创建。我对于为什么它在一种情况下而不是另一种情况下工作一无所知。

Notes完全保存完好,状态历史记录没有。

public void Save()
{
    foreach (var noteDTO in Notes.Where(x => x.NewRecord))
    {
        Loan.Notes.Add(new Note
        {
            Subject  = noteDTO.Subject,
            Comments = noteDTO.Comments,
            Active   = noteDTO.Active,
            Loan     = Loan,
            Loan_Id  = Loan.Id
        });
    }


    foreach (var status in StatusHistory.Where(x => x.Id == 0))
    {
        Loan.StatusHistory.Add(
            new LoanStatusHistory
                {
                    Loan_Id        = Loan.Id,
                    Active         = status.Active,
                    IsCurrent      = status.Current,
                    Date           = status.StatusDate.Value.Date,
                    StatusReason   = status.Reason,
                    LoanStatus_Id  = status.Status_Id.Value,
                    Order          = status.Order.Value,
                    Created        = DateTime.Now,
                    CreatedBy      = CurrentUser.GetInstance().MyUser.Id,
                    Modified       = DateTime.Now,
                    LastModifiedBy = CurrentUser.GetInstance().MyUser.Id
                });
        }             
    }
    UnitOfWork.LoanRepository.Update(Loan);
    UnitOfWork.Save();
}

在Notes和Status模型中,我设置了一个虚拟的贷款关系。

public virtual Loan Loan { get; set; }

在贷款模型中,我设置了与Notes和Status

的虚拟关系
public virtual ICollection<LoanStatusHistory> StatusHistory { get; set; }
public virtual ICollection<Note> Notes { get; set; }

我想知道是否有人可以给我建议或提示来解决这个问题。

0 个答案:

没有答案