I’m using a generic DataTable to List conversion method which I found on this site:
private List<T> ConvertToList<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row =>
{
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name))
{
pro.SetValue(objT, row[pro.Name], null);
}
}
return objT;
}).ToList();
}
it works great, except when I hit null values for integer fields in pro.SetValue. The reason it fails is because pro.SetValue will set a default value for a type if second parameter is null like this: pro.SetValue(objT, null,null).
but my row[IdColumn] return empty object {} instead of null.
The error I’m getting is:
Object of type ‘System.DBNull’ cannot be converted to type
‘System.Nullable`1[System.Int32]’.
when using int?
and
Object of type ‘System.DBNull’ cannot be converted to type
[System.Int32]’.
when using int
How do I handle this case?
check for null first: