Question

I have a created a class to connect with a database (SQL or DB2)

private DbCommand command { get; set; }
private DbConnection connection { get; set; }        

public DataTable FillTableData(String query)
{
    try
    {
        DataTable table = new DataTable();
        using (DbCommand com = command)
        {
             com.CommandType = CommandType.Text;
             com.CommandText = query;
             connection.Open();
             DbDataReader reader = com.ExecuteReader();
             table.Load(reader);
        }
        return table;
    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        connection.Close();
    }
}

In the SQL it works fine, in the DB2 i get an object disposed exception when I run it a seccond time. I don't see why 'command' must be disposed. And how to to avoid this? I can't use a new opperator because I don't know what command I created (SQLcommand or IDB2Command) at this time.

Was it helpful?

Solution

DBCommand is a reference type, which means that a variable that is declared with that type contains only a pointer to some object in memory and not the object itself.

The line

   using(DBCommand com = command)

copies that pointer, leaving the com variable to point to the same object as the command variable. The using statement causes that object to be disposed when the block is completed, leaving command pointing to a disposed object.

A disposed object should not be reused. You are just lucky it works in SQL Server, as that should not be the case according to the .NET specifications.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top