C#C
C#9mo ago
Rename

✅ EF Core 8: System.InvalidOperationException: 'The instance of entity type cannot be tracked..

Hi guys, I'm getting this error
System.InvalidOperationException: 'The instance of entity type 'OccurrenceRule' cannot be tracked because another instance with the key value '{Id: 0b87b74b-c1b9-48f5-954a-2613fbab92d0}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.'


but the thing is for the query where OccurrenceRule is loaded, I'm using AsNoTracking() method since there won't be any changes for that entity anyways.

the first method loads a list of StaffMembers along with the neccessary navigation properties, where this is also included:
//load StaffMember OccurrenceItem
var occurrenceItems = await dbContext.OccurrenceItems
    .Where(oi => EF.Constant(staffMemberIds).Contains(oi.StaffMemberId))
    .Include(oi => oi.Type)
    .Include(oi => oi.Rule)
    .AsNoTracking()
    .ToListAsync();


and I can see that right after that method, if I call dbContext.ChangeTracker.Entries() it throws this error initially in quickwatch, and if I evaluate it again, it shows the list of entries.
if I continue the code execution after it shows the list of entries. I do NOT run into this error at all and the full operation/endpoint completes successfully.

I was under the impression that if I use .AsNoTracking when loading the data, those entries should not be added to the DbContext.ChangeTracker at all

I get the error when I call dbContext.SaveChanges();
any ideas?
Was this page helpful?