InvalidOperationException when try to ExecuteReader() with Oracle Data Access ODP.NET 11.2

George Taskos picture George Taskos · Mar 21, 2011 · Viewed 9k times · Source

It's the first time I HAVE to work with Oracle, and as we all hate to work with foreign stuff while you are working with a specific model some years, although this is our job and we have to make it.

Now i have installed the Oracle 11 g and copied and referenced the Oracle.DataAccess.dll created a method where opens a connection and tries to retrieve some objects from a view that has been created on the server.

Method:

public BindingList<HeaderReceiver> GetHeaderReceivers()
{
    try
    {
        using (OracleConnection db = new OracleConnection(BaseDataAccess.ConnString))
        {
            string cmdText = "select * from p_customer t";
            BindingList<HeaderReceiver> headerReceivers = new BindingList<HeaderReceiver>();

            OracleCommand cmd = new OracleCommand(cmdText) { CommandType = CommandType.Text };
            db.Open();

            OracleDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); <--- Error Occurs HERE!!!

            while (reader.Read())
                headerReceivers.Add(HeaderReceiver.GetInstance(reader));

            CustBranchRepository rep = new CustBranchRepository();
            headerReceivers.ForEach(p => p.DetailsBranch = rep.GetDetailReceivers(p.Id));

            reader.Close();
            db.Close();
            return headerReceivers;
        }
    }
    catch (Exception ex)
    {
        ExporterLogger.Log(ex);
        return null;
    }
}

Now when ExecuteReader() commits I get this InvalidOperationException.

Operation is not valid due to the current state of the object.

The StackTrace:

   at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior)
   at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(CommandBehavior behavior)
   at Exporter.Boss.DataAccess.CustomerRepository.GetHeaderReceivers() in ...Exporter\Exporter.Boss.DataAccess\CustomerRepository.cs:line 25

Any thoughts and help...

Thank you!

Answer

Will picture Will · Mar 30, 2011

It looks like you're missing the connection on the command object...

db.Open();
OracleCommand cmd = new OracleCommand(cmdText) { CommandType = CommandType.Text };
cmd.Connection = db;