Search code examples
c#linqsqlconnection

Do I need to Close Connection when i use using?


I have the following code:

newCustomerDataSourceDataContext db = GetDataContext();
{
    var tId = from t in db._CRM_Ticket_Headers
              from p in db.CRM_Priority_LKPs
              where t.created >= fromDate &&
                  t.created < toDate &&
                  t.priorityId == p.priorityId &&
                  t.statusId == status &&
                  t.employeeUserId == csrId
              select t;
}

Do I have to close the Connection manually, if I add using, and I am using Linq as the following:

using (newCustomerDataSourceDataContext db = GetDataContext())
{
    var tId = from t in db.CRM_Ticket_Headers
              from p in db.CRM_Priority_LKPs
              where t.created >= fromDate &&
                  t.created < toDate &&
                  t.priorityId == p.priorityId &&
                  t.statusId == status &&
                  t.employeeUserId == csrId
              select t;
}

Solution

  • It depends on what you want to happen. If you use the using block, the Dispose method will be called on the context which will close the connection. However, if your application is using lazy loading, that will no longer work.