jaffa
jaffa

Reputation: 27350

DbCommand and connection - why does dispose not close underlying connection?

I've seen this in some legacy code which generates code analysis warnings:

  Database db = DatabaseFactory.CreateDatabase(strDBCon);
  DbCommand dbCommand = db.GetSqlStringCommand(sb.ToString());

  using (IDataReader dataReader = db.ExecuteReader(dbCommand))
  {
     while (dataReader.Read())
     {
     }
     dataReader.Close();  // <-- this is redundant as close is covered by using's implicit dispose
  }
  dbCommand.Connection.Close();
  dbCommand.Dispose();
  db = null;

I've read here on SO that the dbCommand.Connection property must be closed in addition to disposing of the dbCommand. I would have thought that dbCommand would dispose of any child disposable objects, in this case Connection. If this is not the case, why?

Upvotes: 2

Views: 2712

Answers (1)

Grant Thomas
Grant Thomas

Reputation: 45083

Types have a choice in this respect to either take ownership of a thing or just utilise a thing. In your case, and this specifically, all you're doing is passing in an existing instance that you've created and could well be expecting to use again.

If the type was explicitly constructed with an instance of a type passed in, you might expect it to take ownership of that instance, and therefore manage it as part of its disposal pattern, but not in the case of a transient method call.

Upvotes: 3

Related Questions