Ian Grinkraut
Ian Grinkraut

Reputation: 219

The instance of entity type '' cannot be tracked because another instance with the key value '{Id: 13}' is already being tracked

I am writing an API that need to access the value of an entity and check if it has changed (userChangedPairOrSingle).

public ActionResult<ProdutoFabricante> Put([FromBody] ProdutoFabricanteViewModel produtoFabricanteViewModel)
    {
        if (produtoFabricanteViewModel.Invalid)
        {
            return StatusCode(400, produtoFabricanteViewModel);
        }

        try
        {
            var actualProdutoFabricante = produtoFabricanteRepository.GetById(produtoFabricanteViewModel.Id);

            if (produtoFabricanteService.userChangedPairOrSingle(produtoFabricanteViewModel, actualProdutoFabricante.Par))
            {

                if (produtoFabricanteService.produtoFabricanteHasItems(produtoFabricanteViewModel.Id))
                {
                    return StatusCode(400, new { Message = "Não é possível alterar " });
                }
            }

            actualProdutoFabricante = mapper.Map<ProdutoFabricante>(produtoFabricanteViewModel);


            produtoFabricanteRepository.Update(actualProdutoFabricante);
            return Ok(actualProdutoFabricante);
        }
        catch (Exception ex)
        {
            return StatusCode(500, (ex.Message, InnerException: ex.InnerException?.Message));
        }
    }

But when I access the same entity that I am going to Update it gives me the following error:

The instance of entity type 'ProdutoFabricante' cannot be tracked because another instance with the key value '{Id: 13}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

How can I avoid this error?

Upvotes: 2

Views: 6762

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239240

When you're mapping, you're creating a new instance (which isn't tracked) instead of updating the existing instance (which is tracked). Instead, you need to do:

mapper.Map(produtoFabricanteViewModel, actualProdutoFabricante);

That will keep the existing instance, and simply update the property values on it. Then, EF will be fine, because this instance is the same one that's tracked.

Upvotes: 5

Related Questions