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

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

I know what this problem means. It is happening right here _context.Bots.Update(bot);.

The question is: is that a good way to solve this by adding .AsNoTracking() to all GetByXXX methods? Any suggestions?

[HttpPut("{id}")]
public async Task<ActionResult> UpdateAsync([FromRoute] int id, [FromBody] BotCreateUpdateDto botCreateUpdateDto)
{
    if (id != botCreateUpdateDto.Id)
    {
        return BadRequest(new { Error = "Invalid ID." });
    }

    var user = await _userService.GetByEmailAsync(botCreateUpdateDto.Email);

    if (user == null)
    {
        return BadRequest(new { Error = "Invalid e-mail." });
    }

    var cryptoPair = await _cryptoPairService.GetBySymbolAsync(botCreateUpdateDto.Symbol);

    if (cryptoPair == null)
    {
        return BadRequest(new { Error = "Invalid crypto pair." });
    }

    var timeInterval = await _timeIntervalService.GetByIntervalAsync(botCreateUpdateDto.Interval);

    if (timeInterval == null)
    {
        return BadRequest(new { Error = "Invalid time interval." });
    }

    var bot = new Bot
    {
        Id = botCreateUpdateDto.Id,
        Name = botCreateUpdateDto.Name,
        Status = botCreateUpdateDto.Status,
        UserId = user.Id,
        CryptoPairId = cryptoPair.Id,
        TimeIntervalId = timeInterval.Id
    };

    bool updated;

    try
    {
        updated = await _botService.UpdateAsync(bot);
    }
    catch (Exception ex)
    {
        return BadRequest(new { Error = ex.Message });
    }

    if (updated)
    {
        return NoContent();
    }

    return NotFound();
}
public async Task<User> GetByEmailAsync(string email)
{
    return await _context.Users
        .Include(e => e.UserRoles)
            .ThenInclude(e => e.Role)
        .Include(e => e.Bots)
        .SingleOrDefaultAsync(e => e.Email == email);
}
public async Task<CryptoPair> GetBySymbolAsync(string symbol)
{
    return await _context.CryptoPairs
        .Include(e => e.Bots)
        .AsNoTracking()
        .SingleOrDefaultAsync(e => e.Symbol == symbol);
}
public async Task<TimeInterval> GetByIntervalAsync(KlineInterval interval)
{
    return await _context.TimeIntervals
        .Include(e => e.Bots)
        .AsNoTracking()
        .SingleOrDefaultAsync(e => e.Interval == interval);
}
public async Task<bool> UpdateAsync(Bot bot)
{
    _context.Bots.Update(bot);
    var updated = await _context.SaveChangesAsync();
    return updated > 0;
}


Solution 1:[1]

I got same issue like : The instance of entity type 'ClassName' cannot be tracked because another instance with the key value '{Id: 1}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

I resolved with remove this .AsNoTracking() when fetch data from DB.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mahadevan Annamalai