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

前端 未结 11 1935
青春惊慌失措
青春惊慌失措 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:10

    A shorter form can be used:

    return (accountNumber == DBNull.Value) ? string.Empty : accountNumber.ToString()
    

    EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:

    return (accountNumber == null) ? string.Empty : accountNumber.ToString() 
    

提交回复
热议问题