c# - Entity Framework 似乎在缓存数据

标签 c# asp.net-mvc entity-framework

我的问题是,当我编写一个基本的 EF 查询以从数据库中获取数据时,它可以很好地检索数据,但是当我更改 SQL Server 数据库中的数据并重新加载查询时,我会得到相同的数据集,而不是新数据。并且修改后的数据需要一段时间。

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

例如上面的查询会带回

mm.Body = "Test";

然后,如果我将 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);
    }   
}

我访问过许多 SO 帖子:

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

ASP.NET MVC how to disable automatic caching option?

最佳答案

您的 DbContext 实例是静态的:

private static ApplicationDbContext Da = new ApplicationDbContext();

因此,对于每个 AppDomain,它一直存在,直到您回收应用程序池。 DbContext 保存它之前看到的项目的缓存,直到你 call the Refresh() method .

但是不要那样做。不要让它静止。使用 Entity Framework 作为一个工作单元,尽可能缩小范围。每个请求创建一个实例。

关于c# - Entity Framework 似乎在缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31404229/

相关文章:

c# - 使用 VS2010 和 Excel 2010 访问 FormatCondition 的异常

javascript - 在 View 上调用 Jquery 函数

mysql - 不支持嵌套事务

c# - 您可以从 App.Xaml.cs 调用 MainWindow.Xaml.cs 中的函数吗?

c# - 从 float 转换为 TimeSpan

asp.net-mvc - 本地集群上托管的 Service Fabric 托管 Asp.net WebApi 容器应用程序 : 403 - Forbidden : Access is denied.

javascript - MVC FileUpload 文件大小客户端验证

c# - 连接表错误

c# - 为什么 Entity Framework 对具有事务和 RAISERROR 的存储过程抛出事务计数错误?

c# - 焦点抽象