Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How to refresh an Entity Framework Core DBContext?

When my table is updated by another party, the db context in dotnet core still return the old value, how can I force the Db context to refresh?

I've done research but I only found people use Reload method, which is not available in EF core, to force the context to refresh.

Some other solution suggests dispose the context after using, but I get error saying the DB context is created by dependency injection and I should not mess up with it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...