quitstalin
quitstalin

Reputation: 163

Entity Framework doesn't update data value changes made from database

I didn't know quite how to word this. I have an ASP.NET MVC 3 web application with a pretty standard EF 4.1 code first with existing database (non-auto-generated) repository pattern. There's a context which is under a dataservice the web app talks to.

The problem I have is this: say I have a database table with an integer column. The value is 10. If I go into the database itself and enter 25 into the table, no matter how many times I hit refresh on the browser, close the browser and reopen it, clear the browser history, etc, it still persists the value of 10. I have to republish the site.

Why does it do this? Am I blaming the right thing here? Is this an EF problem? an ASP.NET problem? Server problem? ... I don't know where to look into this.

Upvotes: 1

Views: 1371

Answers (1)

Matt Hamilton
Matt Hamilton

Reputation: 204129

Yes, I've struck this problem in my own applications.

The "entities" (object instances) tracked by Entity Framework are cached in memory, and aren't updated when you requery the database, in case overwriting them would clobber any changes you've made to the cached version.

You can get around it by forcing EF to overwrite existing values, but be aware that this will overwrite anything you've changed, so only do it if you know you've saved any pending changes first.

I've written this extension method to do the job:

public static class DbSetExtensions
{
    public static System.Data.Objects.ObjectSet<T> Uncached<T>(this IObjectContextAdapter context)
        where T : class
    {
        var set = context.ObjectContext.CreateObjectSet<T>();
        set.MergeOption = System.Data.Objects.MergeOption.OverwriteChanges;
        return set;
    }
}

So using that, I can say:

var orders = myDbContext.Uncached<Order>().Where(...);

... and the orders set will contain orders that are fresh from the database, overwriting the properties of any Order objects previously queried.

Upvotes: 2

Related Questions