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

前端 未结 11 1927
青春惊慌失措
青春惊慌失措 2020-11-22 06:45

I got the above error in my app. Here is the original code

public string GetCustomerNumber(Guid id)
{
     string accountNumber = 
          (string)DBSqlHel         


        
11条回答
  •  迷失自我
    2020-11-22 07:29

    This is the generic method that I use to convert any object that might be a DBNull.Value:

    public static T ConvertDBNull(object value, Func conversionFunction)
    {
        return conversionFunction(value == DBNull.Value ? null : value);
    }
    

    usage:

    var result = command.ExecuteScalar();
    
    return result.ConvertDBNull(Convert.ToInt32);
    

    shorter:

    return command
        .ExecuteScalar()
        .ConvertDBNull(Convert.ToInt32);
    

提交回复
热议问题