Zen*_*ity 3 c# asp.net-mvc entity-framework
我有一个C#mvc3应用程序,它使用实体框架从我的SQL服务器数据库中提取数据.我发现它似乎是拉"旧"或"缓存"数据而不是当前数据库中的数据.
一旦我更新了模型,它似乎就会提取新数据.
我的问题是如何确保我总是从数据库中提取"实时"数据而不是获取"缓存"或"旧"数据?
当我运行以下代码并检查tblcompanyinfo.companyname的值时,它返回了一个旧的公司名称(与当前在DB中的名称不同).
一旦我更新了模型并重新运行它,它就会返回公司名称的当前值.
private static ApptReminderEntities db = new ApptReminderEntities();
tblCompanyInfo tblcompanyinfo = db.tblCompanyInfoes.SingleOrDefault(t => (t.CompanyID == lCompanyID));
Run Code Online (Sandbox Code Playgroud)
谢谢!
这可能是由于您的共享和静态 DbContext Instance即
private static ApptReminderEntities db = new ApptReminderEntities();
Run Code Online (Sandbox Code Playgroud)
用以下块替换它:
using(ApptReminderEntities db = new ApptReminderEntities())
{
tblCompanyInfo tblcompanyinfo = db.tblCompanyInfoes
.SingleOrDefault(t => (t.CompanyID == lCompanyID));
}
Run Code Online (Sandbox Code Playgroud)
使用using声明,你是
ApptReminderEntities每次实例.因此,对于每次数据库之旅,请使用using以便每次都创建上下文的新实例.