So I am writing, strictly for personal learning, an ORM in C#. I am looping through a database, where the column names match the properties of a class. I am then looping through the properties of the class and assigning the corresponding database column values but i am running into issues casting the return value from the database column.
var PropCollection = type.GetProperties();
foreach (PropertyInfo Property in PropCollection)
{
Property.SetValue(_t, DReader[Property.Name].ToString(),null);
}
I get the expected error:
Object of type ‘System.String’ cannot be converted to type
‘System.Int32’.
Where DReader is just an SQLDataReader returning a column value inside of a loop, say this value is an int, how do I cast it as such??
Property.GetType();
correctly knows the type I need but how do I use that to cast DReader[Property.Name]?
Convert.ChangeTypecan handle all straight conversions.You should not use
DReader[Property.Name].ToString()in your loop. Remove theToString().