Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for DBNull while executing my command only once?

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()?

like image 881
Cyril Gupta Avatar asked Jan 08 '09 01:01

Cyril Gupta


1 Answers

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>();
like image 199
askheaves Avatar answered Dec 19 '22 01:12

askheaves