Entity Framework - Objectstatemanager Error

Asked

Viewed 321 times

0

I am 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 located in the Objectstatemanager. Check that the key values of the given object correspond to the key values of the object to which changes should be applied."}

Error occurs within the below method when calling 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, in the first I had no problems doing the update of the record in the bank, in the second call triggers the error. What I want to know is if you have an easy way to track the problem? What can I check in the code to help me track the error?

  • Just try to add one base.SaveChanges(); after the base.Update(entity);.

1 answer

0

I was able to solve the problem, as all the execution was tied to an external transaction, by changing the Update method to use Transactionscope the problem is gone.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.