EF:插入时重复键

时间:2012-05-22 07:37:56

标签: c# entity-framework

我有以下代码:

public bool AddLeaveFormApprovers(List<LeaveFormApprovers> listToAdd)
{
    bool returnValue=false;
    try
    {
        using (LeaveRegulationEntities db = new LeaveRegulationEntities(ConnectionStringHelper.GetConnectionString(DaConstants.LeaveRegulationEntities)))
        {
            foreach(LeaveFormApprovers approvers in listToAdd)
            {
                approvers.AssignedLeave = db.AssignedLeave
                   .FirstOrDefault(a => a.AssignedLeaveID == approvers.AssignedLeave.AssignedLeaveID);
                approvers.LeaveFormApproverSys = db.LeaveFormApproverSys
                   .FirstOrDefault(a => a.LeaveFormApproverID == approvers.LeaveFormApproverSys.LeaveFormApproverID);
                db.LeaveFormApprovers.AddObject(approvers);
            }                    
            db.SaveChanges();
        }
        returnValue = true;
    }
    catch (Exception ex)
    {
        _Exceptions.ManageExceptions(ex);
    }
    return returnValue;
}

List<LeaveFormApprovers>的列表是从另一个上下文加载的,因为我正在获取当前上下文中的对象:

approvers.AssignedLeave = db.AssignedLeave
    .FirstOrDefault(a => a.AssignedLeaveID == approvers.AssignedLeave.AssignedLeaveID);
approvers.LeaveFormApproverSys = db.LeaveFormApproverSys
    .FirstOrDefault(a => a.LeaveFormApproverID == approvers.LeaveFormApproverSys.LeaveFormApproverID);

我收到以下错误:

  

违反PRIMARY KEY约束'PK_ LeaveFor _B29C651847BE14B9'。无法在对象'dbo.LeaveFormApproverSys'中插入重复键。

1 个答案:

答案 0 :(得分:0)

在生成listToAdd的查询中,尝试附加AsNoTracking()。这应该会阻止EF跟踪实体并稍后尝试重新插入。