Entity Framework: How to refresh the context when data is updated by a separate process

Wednesday, July 20, 2016
by Sean McAlinden

I recently had an interesting problem where I needed a value which was being asynchronously inserted by a separate process.

The Entity Framework was not picking up the newly inserted data which makes sense as the data was inserted outside of its scope.

In my particular case it was crucial I could refresh with the latest data from the database for a specific entity, this led me to add the following method to my repository class:

public void RefreshDatabase(TEntity entity)
        .Refresh(RefreshMode.StoreWins, entity);

As you can see, I cast my DbContext (this.Context) as a context adapter and call refresh on the specified entity.

I have also set the RefreshMode to StoreWins - this means the data from the database should override my local copy.

Anyway, useful little method.

As an aside - this MSDN article shows the use of this method to automatically handle concurrency problems which is an interesting idea.