Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework seems to be caching data

My issue is that when I write a basic EF query to get data from the database, it retrieves the data fine, but when I change the data in the SQL Server database and reload the query, I get the same dataset back, instead of the new data. And it takes a while for the data to be the amended information.

var mm = o.GetContent(page, title);

The above query, for example, would bring back

mm.Body = "Test";

Then if I change Body within the SQL Server database to Test1 and reload the query, it doesn't bring back Test1.

public String GetContent(String page, String title)
{
    var o = new DataContext();

    var mm = o.GetContent(page, title);

    return HttpUtility.HtmlDecode(mm.Body);
}

public class DataContext
{
    private static ApplicationDbContext Da = new ApplicationDbContext();

    public Content GetContent(String page, String title)
    {
        return Da.Content.SingleOrDefault(c => c.Page == page && c.Title == title);
    }   
}

I've visited a number of SO posts:

Prevent Caching in ASP.NET MVC for specific actions using an attribute

ASP.NET MVC how to disable automatic caching option?

like image 372
Geoff Tew Avatar asked Nov 23 '25 10:11

Geoff Tew


1 Answers

Your DbContext instance is static:

private static ApplicationDbContext Da = new ApplicationDbContext();

Hence per AppDomain, so it lives until you recycle the application pool. The DbContext holds a cache of items it's seen before, until you call the Refresh() method.

But don't do that. Don't make it static. Use Entity Framework as a Unit of Work, as narrowly-scoped as possible. Create one instance per request.

like image 92
CodeCaster Avatar answered Nov 25 '25 05:11

CodeCaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!