dimanche 23 août 2020

Activator fails when using string data type

My goal is to retrieve a column of scalar data and convert them into a list of integers.

Suppose, I have the following code snippet:

 public class DataAccess
 {
      SafeDataReader dataReader;

      public IList<T> Get<T>(ITransactionManager tm, string SQL, params object[] parameters)
      { 
          IList<T> list = null;

          while(dataReader.Read())
          {
              T tempO = Activator.CreateInstance<T>();

              Object objValue = dataReader.GetFieldValue(0);

              //... 
              list.Add(tempO);
          }
          

          return list;
     }
     //...
}

Here, T can be either value types or class types.

  • I know how to set values to a class-type.

If T is string, the line

 Tcom tempO = Activator.CreateInstance<Tcom>();

gives the following run-time error:

 No parameterless constructor defined for this object. 

Its usage can be

    DataAccess dataAccess = new DataAccess(); 

    public IEnumerable<int> GetIDs()
    {
        IEnumerable<int> list = null;

        TransactionManager tm = new TransactionManager(DBNameConst.CurrentDB);

        try
        {
            tm.BeginTransaction();

            list = dataAccess.Get<int>(tm, @"select ID from AgeGroup");
            
            tm.CommitTransaction();
        }
        catch (Exception)
        {
            tm.RollbackTransaction();

            throw;
        }

        return list;
    }

Additional source code:

class SafeDataReader
{

   private IDataReader reader = null;

   //...

    public virtual int? GetFieldValue(int columNo)
    {
        
        int? data = null;
        //int column = reader.GetOrdinal(columnName);

        string columnName = reader.GetName(columNo);
        if (!reader.IsDBNull(reader.GetOrdinal(columnName)))
        {
            data = Convert.ToInt32(reader[columnName]);
        }

        return data;
    }

    //...
}




Aucun commentaire:

Enregistrer un commentaire