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

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

    Convert it Like

    string s = System.DBNull.value.ToString();
    
    0 讨论(0)
  • 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() 
    
    0 讨论(0)
  • 2020-11-22 07:12

    Since I got an instance which isn't null and if I compared to DBNULL I got Operator '==' cannot be applied to operands of type 'string' and 'system.dbnull' exeption, and if I tried to change to compare to NULL, it simply didn't work ( since DBNull is an object) even that's the accepted answer.

    I decided to simply use the 'is' keyword. So the result is very readable:

    data = (item is DBNull) ? String.Empty : item

    0 讨论(0)
  • 2020-11-22 07:13

    There is another way to workaround this issue. How about modify your store procedure? by using ISNULL(your field, "") sql function , you can return empty string if the return value is null.

    Then you have your clean code as original version.

    0 讨论(0)
  • 2020-11-22 07:14

    I suppose you can do it like this:

    string accountNumber = DBSqlHelperFactory.ExecuteScalar(...) as string;
    

    If accountNumber is null it means it was DBNull not string :)

    0 讨论(0)
  • 2020-11-22 07:16

    You can use C#'s null coalescing operator

    return accountNumber ?? string.Empty;
    
    0 讨论(0)
提交回复
热议问题