【问题标题】:The instance of entity type '' cannot be tracked because another instance with the key value '{Id: 13}' is already being tracked无法跟踪实体类型“”的实例,因为已在跟踪另一个具有键值“{Id: 13}”的实例
【发布时间】:2020-01-31 20:45:33
【问题描述】:

我正在编写一个 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));
        }
    }

但是当我访问要更新的同一实体时,它会给我以下错误:

无法跟踪实体类型“ProdutoFabricante”的实例,因为已在跟踪另一个具有键值“{Id: 13}”的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。

我怎样才能避免这个错误?

【问题讨论】:

    标签: asp.net-core entity-framework-core asp.net-core-webapi repository-pattern


    【解决方案1】:

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

    mapper.Map(produtoFabricanteViewModel, actualProdutoFabricante);
    

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

    【讨论】:

      猜你喜欢
      • 2023-01-03
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2021-11-24
      • 2020-10-16
      相关资源
      最近更新 更多