Search code examples
c#asp.netoracledbdatareader

Error while read data from database using DbDataReader


I want to read data from an oracle database and add that data in to a List. But when I run the application I'm getting the 'Invalid operation. The connection is closed.' error.

This is my code:

public class NewOtherCompanyMapper
{
    OtherCompany om;
    private Database db;
    private DbCommand cmd;
    private DbConnection con;

     public NewOtherCompanyMapper(OtherCompany om_temp)
    {
        om = om_temp;
        db = DatabaseFactory.CreateDatabase("NDA_generator");
    }

   public List<OtherCompany> getCompanyDetails()
    {
        List<OtherCompany> list = new List<OtherCompany>();
        OtherCompany oc = new OtherCompany();

        try
        {
            con = db.CreateConnection();
            con.Open();

            string query = "SELECT * FROM OtherCompanyData";
            cmd = db.GetSqlStringCommand(query);
            DbDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                oc = new OtherCompany(reader["RegNumber"].ToString(), reader["ComName"].ToString(), reader["Country"].ToString(), reader["Address"].ToString(), reader["CoreBusi"].ToString());
                list.Add(oc);
            }

        }

        catch (Exception ex)
        {
            throw ex;
        }
       return list;
   }
 }

Can you please help me to solve this problem.


Solution

  • Try replacing this

    cmd = db.GetSqlStringCommand(query);
    

    with this:

    cmd = con.CreateCommand();
    cmd.CommandText = query;