I got the above error in my app. Here is the original code
public string GetCustomerNumber(Guid id)
{
string accountNumber =
(string)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidmyApp,
CommandType.StoredProcedure,
"GetCustomerNumber",
new SqlParameter("@id", id));
return accountNumber.ToString();
}
I replaced with
public string GetCustomerNumber(Guid id)
{
object accountNumber =
(object)DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidCRM,
CommandType.StoredProcedure,
"spx_GetCustomerNumber",
new SqlParameter("@id", id));
if (accountNumber is System.DBNull)
{
return string.Empty;
}
else
{
return accountNumber.ToString();
}
}
Is there a better way around this?
A shorter form can be used:
EDIT: Haven't paid attention to ExecuteScalar. It does really return null if the field is absent in the return result. So use instead:
With a simple generic function you can make this very easy. Just do this:
using the function:
I suppose you can do it like this:
If accountNumber is null it means it was DBNull not string :)
String.Concat transforms DBNull and null values to an empty string.
However, I think you lose something on code understandability
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