Home > Net >  How can I check whether or not EF Core has queried the database for an object with the same Id in di
How can I check whether or not EF Core has queried the database for an object with the same Id in di

Time:11-21

For example, my API controller action logic might retrieve a User object by its Id as the first step. Then after some processing, within the same http request, I need the User instance with the same Id again. Somehow the User object can't get passed all through. So at this point, when I call something like dbContext.Users.Find(1) again, how can I know for sure that the DbContext doesn't have to query the database again and instead use the Local tracked version of this User object?

CodePudding user response:

So at this point, when I call something like dbContext.Users.Find(1) again, how can I know for sure that the DbContext doesn't have to query the database again and instead use the Local tracked version of this User object?

You know that because that is guaranteed by the definition of the Find method (which makes it different from FirstOrDefault, SingleOrDefault and similar):

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

So as soon as you use one and the same db context instance (which is the case with ASP.Net Core requests and the db context is registered with scoped lifetime), then the Find method will use the tracked object if exists and won't make database calls.

  • Related