Entity Framework - Error ObjectStateManager

0

I'm getting the following error when trying to update an entity in EF:

{"An object with a key that matches the given object's key could not be found in ObjectStateManager. Please verify that the key values of the supplied object match the key values of the object on which changes are to be applied."}

The error occurs within the method below when you call Update:

 private void ModificarStatus(int id,
                              bool validarMudancaParaCritico, 
                              TipoMedicao tipoMedicao)
    {
        MedidorAutomatico medidorAuto = BpMedidorAutomatico.MedidorAutomaticoPorId(id);
        if (medidorAuto.StatusConformidade != (short)StatusConformidade.Critico &&
            medidorAuto.StatusConformidade != (short)StatusConformidade.Outros)
        {
            medidorAuto.StatusConformidade = (short)StatusConformidade.Atencao;
        }
        if (validarMudancaParaCritico)
        {
            if (medidorAuto.StatusConformidade != (short)StatusConformidade.Outros)
                medidorAuto.StatusConformidade = (short)StatusConformidade.Critico;
        }

        BpMedidorAutomatico.Update(medidorAuto);
    }

    public override MedidorAutomatico Update(MedidorAutomatico entity)
    {
        MedidorAutomatico medidor = base.Update(entity);
        return medidor;
    }

This method in the tests I'm doing is called 2 times, at first I had no problems updating the registry in the bank, the second call triggers the error. What I want to know is if you have an easy way to track down the problem? What can I check in the code to help me locate the error?

    
asked by anonymous 04.05.2016 / 14:07

1 answer

0

I was able to resolve the problem, as the whole execution was tied to an external Transaction, by changing the Update method to use TransactionScope, the problem disappeared.

    public override MedidorAutomatico Update(MedidorAutomatico entity)
    {
        using (TransactionScope transaction = new TransactionScope())
        {
            MedidorAutomatico medidor = base.Update(entity);
            transaction.Complete();
            return medidor;
        }
    }
    
04.05.2016 / 16:56