Enterprise Library Database Connection Close

Topics: Data Access Application Block, Enterprise Library Core, General discussion
Jun 20, 2014 at 5:22 PM
We are using Microsoft Enterprise library to access the sql server database.We are having some doubts about how to close the DB Connection.Code is given below.

DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false);
Database db = new DatabaseProviderFactory().Create("Dataconnectionstring");
string sqlCommand = "";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);
dbCommand.CommandTimeout = 0;
  success = Convert.ToInt32(db.ExecuteScalar(dbCommand));
  return success;
 catch (Exception e)
    throw e;
          so how  can we close database connection
Jun 22, 2014 at 4:53 AM
ExecuteScalar opens a connection and performs the operation(s) and then disposes of the connection (which will close the connection) so there is no need to close the database connection. In this case, Enterprise Library handles this for you. One scenario where you do need to worry about connections is when calling ExecuteReader since this returns an IDataReader which contains an open database connection. The IDataReader should be disposed/closed when done/ The easiest way to do this is with a using block.

Also, technically, in the posted code you should Dispose the DbCommand (although for SqlCommand this is usually not a huge problem (it doesn't cause connections to be orphaned without being closed and returned to the pool).

Randy Levy
Enterprise Library support engineer
Support How-to