EF Core 'another instance is already being tracked'

前端 未结 4 821
情书的邮戳
情书的邮戳 2021-01-11 18:30

I have a problem updating an entity in .Net Core 2.2.0 using EF Core 2.2.3.

An error occurred while saving changes. Error details: The instance of

4条回答
  •  心在旅途
    2021-01-11 18:56

    By default when you retrieve entities they are tracked and since they are tracked you could just call SaveChanges and not call Update. You can also retrieve entities without tracking them by using .AsNoTracking()

    calling Update is needed if not tracked already, so if you use AsNoTracking then you do need to use Update before SaveChanges

    public IQueryable GetAll()
    {    return _context.Anomalies
        .Include(a => a.Asset)
        .Include(a => a.Level);
    }
    
    public async Task GetAnomaly(int anomalyId, User user)
    {
        var anomaly = await GetAll()
            .AsNoTracking()
            .FirstOrDefaultAsync(a => a.Id == anomalyId);
    
        return anomaly;
    }
    

    You can also check if the entity is tracked to know whether to call Update or not:

    using (var transaction = _context.Database.BeginTransaction())
    {
        try
        {
    
            bool tracking = _context.ChangeTracker.Entries().Any(x => x.Entity.Id == anomaly.Id);
            if (!tracking)
            {
                _context.Anomalies.Update(anomaly);
            }
    
            _context.SaveChanges();
    
            transaction.Commit();
        }
        catch (Exception ex)
        {
            transaction.Rollback();
            throw;
        }
    }
    

提交回复
热议问题