无法跟踪实体类型“”的实例,因为已跟踪具有键值“{Id: 13}”的另一个实例

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

我正在编写一个 API 需要访问实体的值并检查它是否已更改 (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));
        }
    }

但是当我访问我要更新的同一个实体时,出现以下错误:

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.

如何避免这个错误?

映射时,您是在创建一个新实例(未跟踪)而不是更新现有实例(已跟踪)。相反,您需要这样做:

mapper.Map(produtoFabricanteViewModel, actualProdutoFabricante);

这将保留现有实例,并简单地更新其上的 属性 值。然后,EF 就没问题了,因为这个实例与跟踪的实例相同。