Friday, March 9, 2012

Nullable got me confused

I have just started on a project which will be based on an existing MS SQL Server database. It has many columns which can be, and sometimes are, null. My basic DataReader code throws an SqlNullValueExceptionwhen I try to GetInt32 but not when I try GetString. Why the difference?

Also, how do I model my class? Do I have to make all fields into nullable types? If I do that I notice a simple GridView will not show a column for that field! I am confused.

I tested with SqlDataReader and I was even unluckier than you: both GetInt32 and GetString returned aSqlNullValueException. So I managed to determine whether the returned data from database is null and then get its value:

SqlDataReader sdr = command.ExecuteReader(CommandBehavior.SequentialAccess);
sdr.Read();
int i= sdr.IsDBNull(1)?0:sdr.GetInt32(1);

|||Doesn't it seem like a huge oversight by the developers? Null values are pretty common in databases, but the SqlDataReader can't handle them.

We are forced to check for null for every column that is nullable in the database, or write our own DataReader. At the same time, some other smart developers created nullable types in C#, so the discrepancy seems even bigger to me: to get a value (possibly null) from a nullable column into a nullable int, I need to go through hoops in order to avoid an exception.

int? x;
if(reader.IsDbNull(0) {
x = null;
} else {
x = reader.GetInt32(0);
}|||

Microsoft created System.Nullables in .NET FCL(framework class library) 2.0 to deal with the known issues in .NET 1.1. Try the thread below for more info. Hope this helps.

http://forums.asp.net/thread/1300858.aspx

No comments:

Post a Comment