3

I have a C# mvc3 application that is using entity framework to pull data from my SQL server database. I discovered that it seemed to be pulling "old" or "cached" data instead of the data that was currently in the DB.

Once I updated the model it seemed to pull the new data.

My question is how do I make sure that I am always pulling "live" data from the database and not getting "cached" or "old" data?

When I ran the following code and checked the value of tblcompanyinfo.companyname it was returning an old company name (different from what was currently in the DB).

Once I updated the model and re-ran it, it returned the current value of company name.

private static ApptReminderEntities db = new ApptReminderEntities();
tblCompanyInfo tblcompanyinfo = db.tblCompanyInfoes.SingleOrDefault(t => (t.CompanyID == lCompanyID));

Thanks!

4

2 回答 2

5

这可能是由于您的共享和静态,DbContext Instance

private static ApptReminderEntities db = new ApptReminderEntities();

将其替换为 using 块,如下所示:

using(ApptReminderEntities db = new ApptReminderEntities())
{
  tblCompanyInfo tblcompanyinfo = db.tblCompanyInfoes
                              .SingleOrDefault(t => (t.CompanyID == lCompanyID));
}

使用using声明,你是

  • ApptReminderEntities每次创建新实例。
  • 在数据库中做任何你想做的事情。
  • 使用是自动关闭和处置您的实例。

因此,对于每次访问数据库,使用using,以便您每次都创建上下文的新实例。

于 2013-06-13T16:52:06.030 回答
1

问题是您没有为每个查询创建新的上下文 - 您已将其定义为静态。

您应该始终ApptReminderEntities为您在数据库上执行的每个操作创建一个新的。

您可以使用存储库模式或类似模式。就我而言,我会做的每一个操作

var employees = new EmployeeRepository().GetEmployees();

在 Employee 存储库构造函数中,它创建了一个new EmployeeEntities()

这也使得单元测试变得非常容易,因为我可以重载我的存储库并传入一个虚拟上下文。

于 2013-06-13T16:52:25.350 回答