0

I Have the follwing Code:

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;
}

The List of List<LeaveFormApprovers> is loaded from another context for that i'm getting the objects in the current context:

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

I'm getting the following error:

Violation of PRIMARY KEY constraint 'PK_LeaveFor_B29C651847BE14B9'. Cannot insert duplicate key in object 'dbo.LeaveFormApproverSys'.

4

1 回答 1

0

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

于 2012-05-22T08:59:20.027 回答