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

huangapple go评论67阅读模式
英文:

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

问题

我有两个数据库表,一个用于食谱,一个用于食材,但当我尝试更新数据库时,它抛出上面的异常。

我的 API 控制器如下:

[HttpPost("saveRecipe")]
public async Task<ActionResult<SaveRecipeResponse>> SaveRecipe(SaveRecipeRequest request, CancellationToken requestAborted)
{
    await _recipeRepo.UpsertAsync(_mapper.Map<RecipeEntity>(request.Recipe), requestAborted);
    foreach (var ing in request.Recipe.Ingredients)
    {
        await _ingRepo.UpsertAsync(_mapper.Map<IngredientEntity>(ing), requestAborted);            
    }
    await _uow.SaveAsync();
    return new SaveRecipeResponse() { Recipe = request.Recipe, Success = true };
}

客户端发送以下请求:

save() {
    this.delegates.recipes.SaveRecipe(this.payload.recipe).subscribe({
        next: (res) => {
            this.isReady = false;
            console.log(res);
        },
        error: (err) => {
            this.isReady = true;
            this.errorMsg = { message: 'save-error', details: err.message };
            console.log(err);
        },
        complete: () => {
            this.isReady = true;
            this.return();
        }
    })
}

如何将所有的食材插入到数据库中?每个食材应该有不同的ID,所以我不知道为什么会抛出这个异常。

英文:

I have two db tables, one for recipes and one for ingredients, but when I try to update the database it throws the exception above.

My api controller is

    [HttpPost(&quot;saveRecipe&quot;)]
    public async Task&lt;ActionResult&lt;SaveRecipeResponse&gt;&gt; SaveRecipe(SaveRecipeRequest request, CancellationToken requestAborted)
    {
            await _recipeRepo.UpsertAsync(_mapper.Map&lt;RecipeEntity&gt;(request.Recipe), requestAborted);
            foreach (var ing in request.Recipe.Ingredients)
            {
                await _ingRepo.UpsertAsync(_mapper.Map&lt;IngredientEntity&gt;(ing), requestAborted);            
            }
await _uow.SaveAsync();
            return new SaveRecipeResponse() { Recipe = request.Recipe, Success = true };
            // &lt;/custom:SaveRecipe&gt;
    }

The client send this request:

save() {
    this.delegates.recipes.SaveRecipe(this.payload.recipe).subscribe({
      next: (res) =&gt; {
        this.isReady = false;
        console.log(res);
      },
      error: (err) =&gt; {
        this.isReady = true;
        this.errorMsg = {message: &#39;save-error&#39;, details: err.message};
        console.log(err);
      },
      complete: () =&gt; {
        this.isReady = true;
        this.return();
      }
    })
  }

how can i insert all of the ingredients in the database? every ingredient should have a different ID so i don't know why does it throw this

答案1

得分: 0

感谢CodeCaster的评论,我发现数据应该只映射一次。所以我现在将映射的实体保存在一个变量中,然后直接使用它。

[HttpPost("saveRecipe")]
public async Task<ActionResult<SaveRecipeResponse>> SaveRecipe(SaveRecipeRequest request, CancellationToken requestAborted)
{
    RecipeEntity r = _mapper.Map<RecipeEntity>(request.Recipe);
    await _recipeRepo.UpsertAsync(r, requestAborted);
    foreach (var ing in r.Ingredients)
    {
        await _ingRepo.UpsertAsync(ing, requestAborted);            
    }

    await _uow.SaveAsync();

    return new SaveRecipeResponse() { Recipe = request.Recipe, Success = true };
}

希望这对您有帮助。

英文:

Thanks to CodeCaster's comment, I found out data should be mapped only once. So I now save the mapped entity in a variable and then use it directly.

[HttpPost(&quot;saveRecipe&quot;)]
// &lt;custom:customAttributesSaveRecipe&gt;
    // &lt;/custom:customAttributesSaveRecipe&gt;
public async Task&lt;ActionResult&lt;SaveRecipeResponse&gt;&gt; SaveRecipe(SaveRecipeRequest request, CancellationToken requestAborted)
{
        // &lt;custom:SaveRecipe&gt;
        RecipeEntity r = _mapper.Map&lt;RecipeEntity&gt;(request.Recipe);
        await _recipeRepo.UpsertAsync(r, requestAborted);
        foreach (var ing in r.Ingredients)
        {
            await _ingRepo.UpsertAsync(ing, requestAborted);            
        }

        await _uow.SaveAsync();

        return new SaveRecipeResponse() { Recipe = request.Recipe, Success 
= true };
        // &lt;/custom:SaveRecipe&gt;
}

huangapple
  • 本文由 发表于 2023年3月8日 19:09:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定