Home > database >  Do Already Tracked Entities in EF Core Get Resolved With Subsequent Data Fetches?
Do Already Tracked Entities in EF Core Get Resolved With Subsequent Data Fetches?

Time:11-05

I am using EF Core 7.

Say I have a User object that is loaded into memory by a middleware. It is tracked and in an UNCHANGED state. Now say later in the request, I fetch some EntityA from the database.

EntityA has a navigation property to the User that created it. In a scenario where the User loaded by the middleware and the creator of EntityA are the same, if I include that navigation property in the EF Core query, will EF Core recognize that it is already tracking that object when it maps the query result or will it throw an exception?

Thanks

CodePudding user response:

will EF Core recognize that it is already tracking that object when it maps the query result

Yes.

Identity resolution happens automatically when entities are tracked from a query. This means that if an entity instance with a given key value is already tracked, then this existing tracked instance is used instead of creating a new instance. This has an important consequence: if the data has changed in the database, then this will not be reflected in the results of the query.

Identity Resolution and Queries

CodePudding user response:

Within the scope of the same DbContext instance reading both entities, yes, EF will associate the already tracked User instance when you fetch the EntityA. The query to retrieve EntityA & eager load it's User will still have the SQL to retrieve that User from the database, however EF will serve back the already tracked user reference with the EntityA(s) returned. It does not automatically merge any data pulled from that query into the tracked User instance. If the User was loaded and tracked by a different DbContext instance than the EntityA query then the separate DbContext instances have no knowledge of what each other are tracking.

When dealing with the same DbContext instance, If you add a .AsNoTracking() to the query to retrieve the EntityA, EF will populate a new User reference to associate with the EntityA despite the fact that the DbContext might already be tracking that User reference. AsNoTracking both tells EF not to add loaded entities into the tracking cache as well as to ignore any entities that might already be in the tracking cache.

  • Related