user194076
user194076

Reputation: 9017

get default value for a type

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?

Upvotes: 2

Views: 1893

Answers (2)

D Stanley
D Stanley

Reputation: 152566

check for null first:

pro.SetValue(objT, row.IsNull(pro.Name) ? null : row[pro.Name], null);

Upvotes: 5

Reed Copsey
Reed Copsey

Reputation: 564451

You probably need to check for DBNull explicitly

if (columnNames.Contains(pro.Name))
{
    if (row.IsNull(pro.Name))
        pro.SetValue(objT, null, null);
    else
        pro.SetValue(objT, row[pro.Name], null);
}

This will handle int?, but trying to convert null to an Int32 (non-nullable) should be an error case.

Upvotes: 1

Related Questions