0

I am trying to fetch record into listarray as follows:

List<Car> lst = new List<Car>();

string str = "select * from Inventory"; 

using(SqlCommand cmd = new SqlCommand(str,this.sqlcon))
{
    SqlDataReader rdr = cmd.ExecuteReader();

    while (rdr.Read())
    {
        lst.Add(new Car 
                    {
                        CarId = (int)rdr["CarId"],
                        Make = (string)(rdr["Make"] ?? ""),
                        Color= (string)(rdr["Color"] ?? ""),
                        PetName = (string)(rdr["PetName"] ?? "")

                    });
    }

    rdr.Close();
}

Make,color and petname may have null values and thus I used the ?? operator. I get the following error

Unable to cast object of type system.dbnull' to 'system.string'.

What is the correct way of checking for null in this scenario?

Cody Gray
  • 230,875
  • 49
  • 477
  • 553
Poongodi
  • 55
  • 5

2 Answers2

8

DBNull isn't the same as null, so you can't use the ?? operator. You have to handle this case separately.

Replace:

Make = (string)(rdr["Make"] ?? ""),

with:

Make =  (rdr["Make"] == System.DBNull.Value ? "" : (string)rdr["Make"]),
fubo
  • 42,334
  • 17
  • 98
  • 130
1

SqlDataReader returns a DBNull object, which is not a C# null - it is an object representing a NULL value in the database.

You have a number of options, and creating a method to handle that might be most readable and save you on repeating code:

private static string GetStringOrEmpty(object dbValue){
    return dbValue == System.DBNull.Value ? string.Empty : (string)dbValue;
}

and then

Make = GetStringOrEmpty(rdr["Make"]),

Alternatively look into Dapper which is a very small but powerful ORM that will handle a lot of this stuff for you.

Gerino
  • 1,873
  • 1
  • 14
  • 21