Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting datareader value to a to a Nullable variable

Tags:

c#

sql

I'm trying to run the following code but get a casting error. How can I rewrite my code to achive the same ?

boolResult= (bool?)dataReader["BOOL_FLAG"] ?? true;
intResult= (int?)dataReader["INT_VALUE"] ?? 0;

Thanks

like image 895
Elad Benda Avatar asked Mar 23 '11 18:03

Elad Benda


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.


2 Answers

Consider doing it in a function.

Here's something I used in the past (you can make this an extension method in .net 4):

public static T GetValueOrDefault<T>(SqlDataReader dataReader, System.Enum columnIndex)
{
    int index = Convert.ToInt32(columnIndex);

    return !dataReader.IsDBNull(index) ? (T)dataReader.GetValue(index) : default(T);
}

Edit

As an extension (not tested, but you get the idea), and using column names instead of index:

public static T GetValueOrDefault<T>(this SqlDataReader dataReader, string columnName)
{

    return !dataReader.IsDBNull(dataReader[columnName]) ? (T)dataReader.GetValue(dataReader[columnName]) : default(T);
}

usage:

bool? flag = dataReader.GetValueOrDefault("BOOL_COLUMN");
like image 132
Giovanni Galbo Avatar answered Sep 19 '22 22:09

Giovanni Galbo


Use the "IsDbNull" method on the data reader... for example:

bool? result = dataReader.IsDbNull(dataReader["Bool_Flag"]) ? null : (bool)dataReader["Bool_Flag"]

Edit

You'd need to do something akin to: bool? nullBoolean = null;

you'd have

bool? result = dataReader.IsDbNull(dataReader["Bool_Flag"]) ? nullBoolean : (bool)dataReader["Bool_Flag"]
like image 27
taylonr Avatar answered Sep 19 '22 22:09

taylonr