2

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?

Community
  • 1
  • 1
Geoff Tew
  • 55
  • 1
  • 6

1 Answers1

8

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.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272