When I retrieve any Scalar value from the database, I usually write code like this for nullable fields.
cmd.ExecuteScalar() == DBNull.Value ? 0 : (int)cmd.ExecuteScalar()
But I don't like it because it executes the Executescalar statement twice. It's an extra trip to the server for my website and in favor of performance I don't want to do this.
Is there any way I can get rid of this extra ExecuteScalar()?
Write yourself an extension method for the sql command.
public static T ExecuteNullableScalar<T>(this SqlCommand cmd)
where T : struct
{
var result = cmd.ExecuteScalar();
if (result == DBNull.Value) return default(T);
return (T)result;
}
Usage becomes:
int value = cmd.ExecuteNullableScalar<int>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With