Search code examples
c#connectionusingodp.net

"Connection must be open for this operation" Exception on ODP


I'm calling OracleCommandd.ExecuteNonquery() in my applciation and i'm getting "Connection must be open for this operation" exception in the code below:

using (OracleConnection connection = new OracleConnection(ConnectionString))
        {
            OracleCommand oracleCommand = new OracleCommand(procedureName, connection);
            oracleCommand.CommandType = CommandType.StoredProcedure;

            oracleCommand.ExecuteNonQuery();
        }

When i place connection.Open(); just after using statement the exception does not occur but isn't using statement handling the opening and closing phase of connection(open close actually menas getting and leaving connection fromt/to connection pool).


Solution

  • but isn't using statement handling the opening and closing phase of connection

    No.
    The using has nothing to do with connection.Open()

    using (OracleConnection connection = new OracleConnection(ConnectionString))
    {
      connection.Open(); //<-- must have
      //rest of code omitted
    }
    

    You don't need to call connection.Close() because that happens when the connection is disposed. Which is the true purpos of the usingkeyword.

    This is what the using actually translate into:

    try
    {
      //code omitted
    }
    finally
    {
      connection.Dispose();
    }