Reputation: 13723
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()?
Upvotes: 7
Views: 5238
Reputation: 755
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>();
Upvotes: 17
Reputation: 146499
object o = cmd.ExecuteScalar();
return (o== DBNull.Value) ? 0 : (int)o;
Upvotes: 4
Reputation: 204219
Just use a variable to cache the result:
var o = cmd.ExecuteScalar();
return o == DBNull.Value ? 0 : (int)o;
Upvotes: 12