Let's say I have this class:
class myclass { public int Field1{ get; set; } public int? Field2 { get; set; } //Note Field2 is nullable }
I am trying to populate a general list with data coming from a database. Since GetSqlInt32 implements INullable, I would have thought that the code below would work. This is not true. It generates an error if Field2 is NULL.
List<myclass> mylist=new List<myclass>(); int Field1_Ordinal = rdr.GetOrdinal("Field1"); int Field2_Ordinal = rdr.GetOrdinal("Field2"); SqlDataReader rdr = cmd.ExecuteReader(); //Execute a stored procedure to retrieve data from the database while (rdr.Read()) { mylist.Add(new myclass { Field1 = rdr.GetSqlInt32(Field1_Ordinal).Value, Field2 = rdr.GetSqlInt32(Field2_Ordinal).Value //Error if field2 is null }); }
Any ideas why this is not working?
null c # datareader
Anthony
source share