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)
);
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;
}
}
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With