Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: How to detect external changes to database

Tags:

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.

like image 327
Mert Akcakaya Avatar asked Sep 16 '13 13:09

Mert Akcakaya


People also ask

How does Entity Framework detect changes?

Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

What does AutoDetectChangesEnabled do?

AutoDetectChangesEnabled to false should disable change tracking requiring one to call DbContext. DetectChanges in order to identify changes to be sent to the database.

How do I use Savechangesasync?

First you create an instance of MyEDM , add the list myList to the table MyTable , then call SaveChanges() to persist the changes to the database. It works how you want, the records get committed, but your program cannot do anything else until the commit finishes.

How does Entity Framework affect the connection with the database?

Because an open connection to the database consumes a valuable resource, the Entity Framework opens and closes the database connection only as needed. You can also explicitly open the connection. For more information, see Managing Connections and Transactions. Once in each application domain.


1 Answers

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.

like image 125
user247702 Avatar answered Sep 29 '22 18:09

user247702