Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Pulling data from cached or old database

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!

like image 614
Zenacity Avatar asked Dec 09 '25 23:12

Zenacity


1 Answers

This may be due to your shared and static DbContext Instance i.e.

private static ApptReminderEntities db = new ApptReminderEntities();

Replace it with using block as below:

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

Using using statement, you are

  • Creating new ApptReminderEntities instance each time.
  • Doing whatever you want in database.
  • Using is automatically closing and disposing your instance.

So, for each trip to database, use using so that you will create new instance of your context each time.

like image 189
Bhushan Firake Avatar answered Dec 12 '25 12:12

Bhushan Firake