我收到一个错误“ 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 中有两个相同的实体键。有没有办法解决这个问题,而无需我去上下文分离实体,或者有其他方法吗?将实体与上下文分离的最佳方法是什么?