I've a method that generates list of class type from data of data reader.
if (datareader != null && datareader .HasRows)
{
Dictionary<string, PropertyInfo> pDict= GetPropertyDictionary<T>();
var fields = GetFieldNames(datareader );
while (datareader .Read())
{
T myobj= new T();
for (int index = 0; index < fields.Count; index++)
{
if (pDict.TryGetValue(fields[index], out PropertyInfo info))
{
var val1 = datareader .GetValue(index);
info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);
}
}
}
}
I have class properties, some of them are nullable.
public string StudentName{ get; set; }
public decimal? percentage{ get; set; }
public int? StudentNumber{ get; set; }
Code works properly for all properties except StudentNumber which is int.
In above code following line throws exeption Object of type 'System.Int16' cannot be converted to type 'System.Nullable`1[System.Int32] :
info.SetValue(myobj, (val1 == DBNull.Value) ? null : val1, null);
What can be done to solve this issue?
(val1 == DBNull.Value) ? null : (int?)val1
work as your ternary? val1's type is Int16 and not nullable, so it doesn't match the type expectation set by returning null in the first expression. – Flatting