Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF4 - Data not getting refreshed/updated

I have a MVC3 app that uses EF4 POCO/repositories. Whenever a item is opened by the user on the website it is flagged in the database. There is a backend service that keeps checking if there are any items that have been flagged for more 'x' seconds and unflags them. The issue that I am running into is in my backend service the query that I run seems to find the flagged items but when I check the individual item for being flagged the entity hasn't refreshed.

Here is my code that looks for the flagged items

 var list = Context.Transactions
            .Where(t => t.Locked).ToList() ;

The list.Count() returns me the correct number. But when I start iterating thru' the list I find that t.Locked = false

When I run the SQL profiler I can see that for my above code data is retrieved from the database correctly. Is this caching or a identity map issue that I am not using the EF correctly.

like image 940
kolhapuri Avatar asked May 05 '11 21:05

kolhapuri


1 Answers

Read very carefully this answer. After that I recommend you to refactor your application to use a new context for each request (in case of web) and new context for each time event in backend service.

EF uses identity map pattern. Once the entity is loaded by the context you will by default always get the same instance with same values despite the data returned from new query. There are ways to force EF to refresh the entity but it is mostly for solving some concurrency issues.

If you are still not convicted to change your application use this to force refreshing values:

var query = (ObjectQuery)(yourLinqQuery);
query.MergeOption = MergeOption.OverwriteChanges;
// Now iterate / execute query
like image 92
Ladislav Mrnka Avatar answered Dec 25 '22 21:12

Ladislav Mrnka