13

how we read integer null values from Sql Data Reader

SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
    mb.Id = (int)reader["Id"];
    mb.Mem_NA = (string)reader["Mem_NA"];
    mb.Mem_ResAdd4 = reader["Mem_ResAdd4"] == System.DBNull.Value ? null : (string)reader["Mem_ResAdd4"];
    //
   mb.Mem_ResPin = reader["Mem_ResPin"] as  int? ?? default(int);
  // shows the error "Object cannot be cast from DBNull to other types."
 }

mb.Mem_ResPin cant read from reader

 CREATE TABLE [dbo].[Mem_Basic] (
[Id]          INT           IDENTITY (1, 1) NOT NULL,
[Mem_NA]      VARCHAR (100) NOT NULL,
[Mem_ResAdd4] VARCHAR (100) NULL,
[Mem_ResPin]  INT           NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
3
  • What is mb.Mem_ResPin declared as?
    – ChrisF
    Commented Aug 30, 2013 at 10:32
  • 2
    I know we've already had this conversation, but "dapper" would just make this work without you banging your head against ADO.NET every step of the way... just sayin' - there's a reason we wrote it... to avoid exactly this kind of pain Commented Aug 30, 2013 at 10:33
  • @Marc, and I can fully attest to why Dapper is the best ORM on the market today! And it's free no less! Commented Aug 30, 2013 at 12:33

8 Answers 8

17

Just convert it, like you do in previous row

mb.Mem_ResAdd4 = reader["Mem_ResAdd4"] == System.DBNull.Value ? null : (string)reader["Mem_ResAdd4"];
//
    mb.Mem_ResPin = reader["Mem_ResPin"]== System.DBNull.Value ? default(int):(int)reader["Mem_ResPin"]
2
  • shows the eror "Object cannot be cast from DBNull to other types."
    – neel
    Commented Aug 30, 2013 at 10:37
  • see my response for DBNull treatment Commented Aug 30, 2013 at 10:42
9

I use a generic extension method for all DB casts:

public static T? DbCast<T>(this object dbValue)
        where T : struct
    {
        if (dbValue == null)
        {
            return null;
        }
        if (dbValue is System.DBNull)
        {
            return null;
        }
        T? value = dbValue as T?;
        if (value != null)
        {
            return value;
        }
        var conv = dbValue as IConvertible;
        if (conv != null)
        {
            value = (T)conv.ToType(typeof(T), CultureInfo.InvariantCulture);
        }
        return value;
    }

It tries to treat every situation we encountered so far. Adjust conditions as needed for you.

Usage:

int? value = reader["Mem_ResAdd4"].DbCast<int>()
5

Write a simple wrapper e.g. as an extension method and check for IsDBNull inside:

public static int SafeGetInt(this SqlDataReader reader, string colName)
{
    var colIndex = reader.GetOrdinal(colName);
    return !reader.IsDBNull(colIndex) ? reader.GetInt32(colIndex) : default(int);
}

usage:

var result = reader.SafeGetInt(colName);
5

You can use SqlDataReader.GetSqlInt32 to handle Nullable<int>:

SqlInt32 resPin = reader.GetSqlInt32(reader.GetOrdinal("Mem_ResPin"));
mb.Mem_ResPin = resPin.IsNull ? (int?) null : resPin.Value;
3

Maybe try this extention:

public static class Helper
{
    public static T GetSafe<T>(this SqlDataReader reader, string name)
    {
        var value = reader[name];
        return value == DBNull.Value ? default(T) : (T) value;
    }
}

and use like this:

        if (reader.Read())
        {
            Mb mb = new Mb();
            mb.Id = reader.GetSafe<int>("Id");
            mb.Mem_NA = reader.GetSafe<string>("Mem_NA");
            mb.Mem_ResAdd4 = reader.GetSafe<string>("Mem_ResAdd4");

            mb.Mem_ResPin = reader.GetSafe<int>("ResPin");
        }
2

There are a few approaches here. Unfortunately, DBNull makes this vexing - the reader[name] API returns an object that could be your value, or that could be DBNull.Value - so you have to check for that (is) and handle it. The other approach is to use the reader.IsDBNull(ordinal) API, but as you will note : that needs an ordinal (column index) rather than a name. In either case, you can add things like utility methods to help:

static object Read(IDataReader reader, string name)
{
    var val = reader[name];
    return val is DBNull ? (object)null : val;
}

then (for example):

mb.Mem_ResPin = (int?)Read(reader, "Mem_ResPin")

However, again: tools like "dapper" might make this a lot easier for you; a single Query<T>(tsql, args).SingleOrDefault() would deal with all of this, including nulls, Nullable<T>, and a range of other scenarios.

2
  • This code would result in a cast error on casting to (int?). You first need to unbox to a regular int. Commented Aug 30, 2013 at 11:43
  • @MennovandenHeuvel no, you don't. Try it. Worse: unboxing to int (rather than int?) would actually make it throw a NullReferenceException whenever the value is null (which is explicitly an expected scenario here) Commented Aug 30, 2013 at 11:49
2
public static class SqlDataReaderExtensions
{
    public static T Value<T>(this SqlDataReader reader, string name, T defaultValue = default)
    {
        var val = reader[name];

        if (val == DBNull.Value)
            return defaultValue;

        return (T)val;
    }
}
1

Compare is against DBNull.

var resPin = reader["Mem_ResPin"];
if(!Convert.IsDBNull(resPin))
  mb.Mem_ResPin = resPin as int?;
else
  mb.Mem_ResPin = new Nullable<int>();
1
  • Are you sure mb.Mem_ResPin is an int? type?
    – keyboardP
    Commented Aug 30, 2013 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.