© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•10mo ago•
7 replies
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.'
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();
//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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ EF: Instance of Entity Type cannot be tracked (already being tracked)
C#CC# / help
8mo ago
The instance of entity type 'OptimizerInstanceEntity' cannot be tracked
C#CC# / help
2y ago
InvalidOperationException - EF Instance - Identity Resolution
C#CC# / help
4y ago
❔ Generic entity type in EF Core
C#CC# / help
4y ago