How to refresh an Entity Framework Core DBContext?

Oh, this issue had me in knots for days.

I’m using Visual Studio 2017 with .Net Core 2.1, and my EF Core code looked something like this:

//  1.  Load a [User] record from our database 
int chosenUserID = 12345;
User usr = dbContext.Users.FirstOrDefault(s => s.UserID == chosenUserID);

//  2. Call a web service, which updates that [User] record
HttpClient client = new HttpClient()
await client.PostAsync("http://someUrl", someContent);

//  3. Attempt to load an updated copy of the [User] record
User updatedUser = dbContext.Users.FirstOrDefault(s => s.UserID == chosenUserID);

At step 3, it would simply set “updatedUser” to the original version of the [User] record, rather than attempting to load in a fresh copy. So, if, after step 3, I modified that [User] record, I’d actually lose whatever settings the web service had applied to it.

I – eventually – found two solutions.

I could change the ChangeTracker settings. This worked, but I was concerned about the side-effects of doing this:

dbContext.ChangeTracker.QueryTrackingBehavior = Microsoft.EntityFrameworkCore.QueryTrackingBehavior.NoTracking;

Or, I could slip in the following command, before attempting to reload the [User] record…

await dbContext.Entry(usr).ReloadAsync();

This seems to force .Net Core to reload that [User] record, and life is good again.

I hope this is useful…

Tracking down, and fixing this bug took me days….

There’s also an excellent article describing the various ways to get around this caching issue here.

Leave a Comment