Home > OS >  EF Core Context does not contain changes for added entities
EF Core Context does not contain changes for added entities

Time:09-28

I have .NET Core 3.1 Web API with EF Core 3.1. I have DbContext with Scoped lifetime.

I have two services where I inject DbContext in the constructor. When I update the existing entity in Service1 (and not call SaveChanges, just context.Update) then I can see an updated entity in context in Service2 (during one request of course).

BUT

When I create a new entity in Service1 (and not call SaveChanges, just context.Add) then this entity is absent in context in Service2.

Why does it happen and is it possible to fix it to have added entities in any service where I inject context?

CodePudding user response:

When you issue a database query (without specifying the AsNoTracking option), the context will throw away the loaded data for any entities it is already tracking, and return the existing instance instead. This is why your service is seeing the updated details for the entities which have not been saved.

However, since the database query won't return any details for the entities which have been added but not yet saved, they will not be included in the results of the query.

If you want to see the pending changes, you would need to query the DbSet<TEntity>.Local collection instead.

Change Tracking in EF Core

  • Related