29

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 entity type 'Asset' 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 using

This is how the DB Context is registered:

services.AddDbContext(options =>

options.UseSqlServer(Configuration.GetConnectionString("DbConnection")), ServiceLifetime.Scoped);

The Scoped lifetime is set by default but I wrote it to be more easy to understand.

The Anomaly object is got like this:

public IQueryable<Anomaly> GetAll()
    {return _context.Anomalies.Include(a => a.Asset).Include(a => a.Level)
}

public async Task<Anomaly> GetAnomaly(int anomalyId, User user)
{
    var anomaly = await GetAll()
        .FirstOrDefaultAsync(a => a.Id == anomalyId);

    return anomaly;
}

And the Update() method looks like this:

using (var transaction = _context.Database.BeginTransaction())
{
    try
    {
        _context.Anomalies.Update(anomaly);
        _context.SaveChanges();

        transaction.Commit();
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        throw;
    }
}

It contains some checks before this transaction, but none relevant enough in this context.

This is where I get the error with instance already being tracked. I can't understand how this happens .. If the context is Scoped, then

... "a new instance of the service will be created for each scope", in this case, for each request

If my context on the PUT request is different from the context of the GET request, how is the entity already being tracked? How does this work at the most basic levels?

The only way to make it work is to set the state for all entries from the ChangeTracker to EntityState.Detached. Then it works.. but it makes no sense, at least to my current knowledge..

I found this question but with no valid answer, only with workarounds and assumptions about how EF does the tracking.


UPDATE Here is a link to bitbucket with a sample recreating this problem: EF Core Update Sample

I serialized the objects retrieved from the context.

With Tracking on the LEFT <====> With NO tracking on the RIGHT With Tracking on the LEFT <====> With NO tracking on the RIGHT

4
  • 1
    there is more than 1 context instance per request. As you mentioned. using Detach is not a valid solution here you need to find the root cause. How you inject _context type?
    – ilkerkaran
    May 21, 2019 at 14:47
  • "It contains some checks before this transaction, but none relevant enough in this context." Are you sure? Is _context.Set<Asset>().Local.Count == 0 true before calling _context.Anomalies.Update(anomaly);?
    – Ivan Stoev
    May 21, 2019 at 14:49
  • @Ivan, it seems that _context.Set<Asset>().Local.Count == 0 is false. I ended up commenting all the code before that check and it still is false.. May 21, 2019 at 15:35
  • @ilkerkaran, I inject the _context in the constructor like this: public AnomalyManager(SAMSDbContext context){_context = context;} where _context is a private readonly field. In the original question I posted how the DbContext is registered in the Startup.cs May 21, 2019 at 15:38

6 Answers 6

24

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<Anomaly> GetAll()
{    return _context.Anomalies
    .Include(a => a.Asset)
    .Include(a => a.Level);
}

public async Task<Anomaly> 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<Anomaly>().Any(x => x.Entity.Id == anomaly.Id);
        if (!tracking)
        {
            _context.Anomalies.Update(anomaly);
        }

        _context.SaveChanges();

        transaction.Commit();
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        throw;
    }
}
8
  • 1
    I tried this but doesn't work. Even with .AsNoTracking() before `Include(), even after it, same result .. May 21, 2019 at 15:52
  • strange it works for me, I've updated my answer to show how to detect if the entity is tracked which can be used to decide if to call Update or not. May 21, 2019 at 16:59
  • I've edited my answer, it seems .AsNoTracking should be after all the .Includes May 21, 2019 at 18:53
  • 1
    I checked that question, it's not working for me. I'm not sure if it's because .NET Core, or why.. Tried with the QueryTrackingBehavior field as well, no improvements. I start to belive something is wrong on another level, maybe my setup is wrong, my config or something like this.. Will come with an update when I find something May 22, 2019 at 5:29
  • 1
    I know Joe, I removed the Update call but with no success. Without it no changes reach the database.. May 22, 2019 at 13:06
6

I was trying to update the same data without noticing. It took me ten hours to realize that. If you have duplicate values like mine,i suggest remove that data... The person who reading this answer may have tried all the solutions on the internet like me, ruined the project, stuck the same error, and omitted duplicate data just like me. You are not alone my friend.

model.GroupBy(gb => gb.ID).Select(s=>s.First()).ToList();//remove duplicates!!!!!
1
  • Good advice, thank you! It seems that this will be a collection of possible solutions for a problem that we all face at some point. Nov 28, 2019 at 11:05
1

I know that I am extremely late to this discussion but I was having the same issue where I could create an entity without issue, but when it came to updating that entity it would succeeded the first time but fail every time thereafter. So I tried all of the suggestions above to no avail. I did some digging around in the docs and found that once I called DbContext.SaveChanges() there was another method that I could call DbContext.ChangeTracker.Clear(). This method is supposed to clear the change tracker of all tracked entities so you can proceed with your future updates. Hopefully, this finds anyone that is having the same frustration with updating entities.

ChangeTracker.Clear() Documentation

0

So, in the end we ended up using a custom UpdateEntity method to save our changes on some entities. This method goes through each property, navigation property and collection property of an entity, makes sure there is no chain and updates the objects a single time.

It works for big objects and we only use it in those cases. For simple operations we keep using the simple Update

Here is the link to a bitbucket repository with the source code

In order to use this method, you will have to get the db entity first. Then call UpdateEntity method with the db entity and your entity received by the request.

I hope it helps you as it helped me. Cheers!

0

I had the same issue but trying to add a second row to the same Entiy. In my case it was because I was assuming the primary key was an Int Identity and auto-generated. As I wasn't assigning any value to it, the second row had the same Id, which is cero default. Lesson learned, when you see this error during an Add() operation in EF, make sure your key is IDENTITY if that's your intention.

0

The issue in my case comes from the fact that the entity in a class definition was missing when updating list in 1:many relation.

public class Exercise
{
  public Guid Id { get; set; } 
  //other props...
  public List<EntityInExercise> Entities { get; set; } = new();
}

public class EntityInExercise
{
  public Guid Id { get; set; } 
  //other props...

  //👇this line was missing 👇
  public Exercise Exercise{ get; set; }= null!;
  //☝️
}

In both cases (with and without the missing line) it creates the same db. The only problem I had was when trying to update that list with Automapper and its Collections.

1
  • It's not obvious how that would cause this error which is all about duplicated primary keys. A reference is never (part of) a primary key. Aug 4, 2021 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.