I have the following ado.net code, if I already use using to wrap my DBCommand, do I have to close the underneath connection explicitly?
Thanks,
public static void ExecuteSQL(int Id)
{
Database db;
const string sqlCommand = "Stored Procedure Name";
try
{
db = DatabaseFactory.CreateDatabase();
using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
{
db.AddInParameter(dbCommand, "p_Id", DbType.Int32, Id);
db.ExecuteNonQuery(dbCommand);
**//do I have to close connection explicitely here??**
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
dbCommand.Connection.Dispose();
}
}
catch (Exception ex)
{
Logger.Log.Error(ex.StackTrace, ex);
throw;
}
}
Yes, if all you have wrapped in the
usingblock is theDbCommand, then you will have to explicitly close theDbConnection, as you currently do in your code. It is sufficient, however, simply to callDispose. You do not need to call bothCloseandDispose.