ef-code-firstdbcontextobjectstatemanager

Entity Framework Code First DBContext ObjectStateManager Error


I am getting an Error "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;
        }

I know that when I call CheckIfNameChanged(TestObject testObject) method i added an Entity Key to the ObjectContext and when i attach or edit the code when i call the _unitOfWork.TestObjectRepository.Update(testObject):

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

This is where the conflict happen and i got two same entity key in the ObjectStateManager. Is there a way to solve this problem without me going to the Context to detach the entity or is there some other way? And what is the best way to detach an entity from the context?


Solution

  • You can check if name changed as follows

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