Search code examples
.netdatareader

Unable to cast DBNull to string


In my ASP.NET WEB API application which is using Signalr I am using below code

 using (var reader = command.ExecuteReader())
                    return reader.Cast<IDataRecord>()
                        .Select(x => new CustomerInfo()
                        {
                            CustomerName = x.GetString(0),
                            CustomerAddress = x.GetString(1),

                        }).ToList();

This is working fine when I have both CustomerName and CustomerAddress in the database. but it failed when I have any one of the column NULL. I am getting below run time error

Unable to cast object of type 'System.DBNull' to type 'System.String'.

How can I handle this?


Solution

  • You can do it with the as keyword: x[0] as string

    using (var reader = command.ExecuteReader())
        return reader.Cast<IDataRecord>()
                     .Select(x => new CustomerInfo()
                     {
                         CustomerName = x[0] as string,
                         CustomerAddress = x[1] as string,    
                     }).ToList();