Entity Framework DB updating but DB context not showing updates

c# entity-framework entity-framework-6 identityserver4 unit-testing


I have the following setup:

  • A .NetCore Web API using EF6 for IdentityServer4.
  • A unit test project that tests the API.
  • DB context is retrieved from the web host's services so should be a singleton and the same reference.

With the following steps leading to my issue:

  1. Before the test I populate the DB with a resource and some claims.
  2. The unit test makes a HTTP DELETE request which results in a claim being deleted. This is visible in the DB as context.SaveChanges() is called.
  3. The unit test then asserts that the claim has been deleted by using the DB context. This fails due to the context not appearing to update.

The issue is that the EF DB context in the unit test appears to not see the deletion of the claim that the API's DB context made.

Things I have tried:

  • Used web host services to retrieve the DB context using _host.Services.GetServices<ConfigurationDbContext>().First(service => service.GetType() == typeof(ConfigurationDbContext)).
    • I have checked through running that there is only one ConfigurationDbContext in existence within the services.
  • Reloading the unit test's context resource entry using context.Entry(resource).Reload().
  • Re-retrieved the context from the web host.


  • The unit test's context appears to be up-to-date before the deletion.
  • Deleting the resource instead of one of its claims seems to be tracked by the unit test's context.
  • The DB is as expected so the code under tests appears to be working as expected it is just the unit test's context that is not updating.
  • The DB context within the API while stepping through is updating leading to and after the context.SaveChanges() call.


  • Has anyone encountered an issue where a EF DB context does not update?
  • Is there a hard refresh method I am missing that would force a re-evaluation of the contexts's state with regards to the referenced DB?
  • Is there a cache of some sort that makes the unit test's DB context believe it is up-to-date.

Many thanks in advance.

10/1/2018 3:38:05 PM

Popular Answer

Thanks to both Eric J and DevilSuichiro for helping me resolve my issue. The problem was that I should not have been trying to use the same DB context. By retrieving a new DB context instead of trying to reuse the same DB context I was able to verify my test results.

Many thanks again.

10/2/2018 3:18:41 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow