Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable integer values from reader

Tags:

c#

sql

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)
);
like image 647
neel Avatar asked Aug 30 '13 10:08

neel


2 Answers

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;
    }
}
like image 171
Kamil OZTURK Avatar answered Sep 27 '22 20:09

Kamil OZTURK


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"]
like image 28
MikkaRin Avatar answered Sep 27 '22 20:09

MikkaRin