Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null safe way to get values from an IDataReader

(LocalVariable)ABC.string(Name) = (IDataReader)dataReader.GetString(0);

This name value is coming from database.

What happening here is if this name is null while reading it's throwing an exception?

I am manually doing some if condition here. I don't want to write a manual condition to check all my variables.

I am doing something like this now..

String abc = dataReader.GetValue(0);
if (abc == null)
   //assigning null
else
   //assigning abc value

Is there something like can we write extension method for this?

like image 585
kumar Avatar asked Apr 09 '10 18:04

kumar


People also ask

How does ado net handle null value?

For working with database ANSI SQL null values, use System. Data. SqlTypes nulls rather than Nullable. For more information on working with CLR value nullable types in Visual Basic see Nullable Value Types, and for C# see Nullable value types.


1 Answers

Here is a couple extension methods that will nicely wrap up all of your concerns around retrieving strongly typed values from a data reader. If the value is DbNull the default of the type will be returned. In the case of string which is a class, a null will be returned. If the field was int, then 0 would be returned. Additionally, if you are expecting an int?, say from an nullable int field, null would be returned.

Specific Usage for Kumar's case:

string abc = datareader.GetValueOrDefault<string>(0);

General Usage

var name = GetValueOrDefault<string>(reader, "Name");

or

var name = reader.GetValueOrDefault<string>("Name");

or

var name = reader.GetValueOrDefault<string>(0);

Extension

public static class NullSafeGetter
{
   public static T GetValueOrDefault<T>(this IDataRecord row, string fieldName)
   {
       int ordinal = row.GetOrdinal(fieldName);
       return row.GetValueOrDefault<T>(ordinal);
   }

   public static T GetValueOrDefault<T>(this IDataRecord row, int ordinal)
   {
       return (T)(row.IsDBNull(ordinal) ? default(T) : row.GetValue(ordinal));
   }
}

from http://skysanders.net/subtext/archive/2010/03/02/generic-nullsafe-idatarecord-field-getter.aspx

like image 93
Sky Sanders Avatar answered Sep 17 '22 21:09

Sky Sanders