简体   繁体   English

实体框架似乎正在缓存数据

[英]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. 我的问题是,当我编写基本的EF查询以从数据库中获取数据时,它可以很好地检索数据,但是当我更改SQL Server数据库中的数据并重新加载查询时,我会得到相同的数据集,而不是新数据。 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 . 然后,如果我将SQL Server数据库中的Body更改为Test1并重新加载查询,它不会带回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: 我访问了许多SO帖子:

Prevent Caching in ASP.NET MVC for specific actions using an attribute 防止使用属性在ASP.NET MVC中缓存特定操作

ASP.NET MVC how to disable automatic caching option? ASP.NET MVC如何禁用自动缓存选项?

Your DbContext instance is static: 您的DbContext实例是静态的:

private static ApplicationDbContext Da = new ApplicationDbContext();

Hence per AppDomain, so it lives until you recycle the application pool. 因此,对于每个AppDomain,它一直存在直到您回收应用程序池为止。 The DbContext holds a cache of items it's seen before, until you call the Refresh() method . 调用Refresh()方法之前, DbContext保存以前看到的项目的缓存。

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. 每个请求创建一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM