7

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.

1 Answer 1

12

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.