0

I just in started working an a proj that uses LINQ to SQL. I noticed the code is not using iDisposable, i myself would never pass a DataContext However since it is created in 1 method and passed to another do I need to do db.Dispose() 2 times, once per method or just once on the method that created the instance of DataContext?

  protected void btnSaveCC_Click(object sender, EventArgs e)
        {
            var db = new DataContext();
            CCBadgeInfo(db);
        }


  private void saveCCInfo(DataContext db)
        {
            var currentCase = (Case)HttpContext.Current.Items["CurrentCase"];

            if (currentCase.TypeId == (int)prj.Constants.Constant..CreditFraud)
            {
                var applicant = db.Applicants.Where(a => a.ApplicantId == currentCase.ApplicantId).SingleOrDefault();
                applicant.CCExpirationDate = tryConvertDateTime(txtCCExpirationDate.Text);
            }

            db.SubmitChanges();
        }
China Syndrome
  • 953
  • 12
  • 24
  • Consensus is: no, there is no need to dispose: http://stackoverflow.com/questions/821574/c-sharp-linq-to-sql-should-datacontext-be-disposed-using-idisposable – Pleun Nov 11 '14 at 20:01
  • And where is the code of your CCBadgeInfo ? – Pleun Nov 11 '14 at 20:05

1 Answers1

0

You should only call it once. However, there shouldn't be any harm to call Dispose more than once: Should IDisposable.Dispose() be made safe to call multiple times?

In your case, you can either

protected void btnSaveCC_Click(object sender, EventArgs e)
{
    using (var db = new DataContext()) {
        CCBadgeInfo(db);
    }
}

Or just create and Dispose DataContext in saveCCInfo method.

Community
  • 1
  • 1
Vince
  • 620
  • 1
  • 5
  • 9