实体框架代码第一个DBContext ObjectStateManager错误

时间:2011-07-16 05:54:27

标签: ef-code-first dbcontext objectstatemanager

我收到错误“An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

public class TestObject
{
    public string Name {get;set;}
}


public EditTeamResponse Edit(TestObject testObject)
    {            
        if (!ValidateTestObject(testObject))
        {
            return testObject;
        }
        try
        {
            _unitOfWork.TestObjectRepository.Update(testObject);
            _unitOfWork.Commit();
        }
        catch (Exception)
        {
            //Error is thrown here
            _validationDictionary.AddError("Unknown", "Unknown Error!");
            return testObject;
        }
        // Other Extra Code
        return editTeamResponse;
    }

protected bool ValidateTestObject(TestObject testObject)
    {
        if (CheckIfNameChanged(teamToValidate))
        {
            if (_unitOfWork.TestObjectRepository.Any(x => x.Name == testObject.Name))
                _validationDictionary.AddError("Name", "Name already exist.");
        }
        return _validationDictionary.IsValid;
    }
private bool CheckIfNameChanged(TestObject testObject)
        {
            return _unitOfWork.TestObjectRepository.FindBy(testObject.TeamId).Name != testObject.Name;
        }

我知道当我调用CheckIfNameChanged(TestObject testObject)方法时,我向ObjectContext添加了一个实体键,当我调用_unitOfWork.TestObjectRepository.Update(testObject)时我附加或编辑代码:

public void Update{
    _context.Entry(entity).State = EntityState.Modified;
}

这是发生冲突的地方,我在ObjectStateManager中获得了两个相同的实体键。有没有办法解决这个问题,而我没有去上下文来分离实体或者还有其他方法吗?什么是将实体与上下文分离的最佳方法?

1 个答案:

答案 0 :(得分:1)

您可以检查姓名是否更改如下

private bool CheckIfNameChanged(TestObject testObject)
{
    return !_unitOfWork.TestObjectRepository
       .Any(x => x.TeamId == testObject.TeamId && x.Name == testObject.Name);
}