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

asp.net-core asp.net-core-webapi entity-framework-core repository-pattern

Question

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?

1
0
10/2/2019 2:35:35 PM

Accepted Answer

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.

1
10/2/2019 6:22:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow