简体   繁体   中英

Entity Framework: How to detect external changes to database

I have a stored procedure that changes lots of data in the database. This stored procedure is called from the application that at the same time uses EF for data operations.

So I click a button, stored procedure is run at the database, data is changed and EF shows old data to the user.

Is there a way to force the DbContext or ObjectContext to refresh data from database? ObjectContext.Refresh() may be the solution but I do not want to call this method for every single table that may be changed. I want all the tables to be refreshed in one move.

I am using Entity Framework 5, targeting .NET 4.0

EDIT: Added data is available but modification on existing data is not reflected by EF. I see the newly added records but I cannot see the changes I made to existing records.

Your DbContext should be short-lived. Create it, run your query, and dispose it.

using (var context = new MyProject.DbContext())
{
    // run your query here
}

Don't keep your context around. That way you won't have any issues with old data.

db = new DbContext())
var context= ((Infrastructure.IObjectContextAdapter)db).ObjectContext;
context.Refresh(Core.Objects.RefreshMode.StoreWins, context.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged | EntityState.Modified))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM