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

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

    I use an extension to eliminate this problem for me, which may or may not be what you are after.

    It goes like this:

    public static class Extensions
    {
    
        public String TrimString(this object item)
        {
            return String.Format("{0}", item).Trim();
        }
    
    }
    

    Note:

    This extension does not return null values! If the item is null or DBNull.Value, it will return an empty String.

    Usage:

    public string GetCustomerNumber(Guid id)
    {
        var obj = 
            DBSqlHelperFactory.ExecuteScalar(
                connectionStringSplendidmyApp, 
                CommandType.StoredProcedure, 
                "GetCustomerNumber", 
                new SqlParameter("@id", id)
            );
        return obj.TrimString();
    }
    

提交回复
热议问题