1
Vote

ReliableSqlConnection does not handle well ExecuteScalar with NULL results

description

If you use ReliableSqlConnection.ExecuteCommand<T> with a select which :
  1. returns a null value
  2. use int or int? as type parameter
The method will always fails with an InvalidCastException.

What is wrong is that ExecuteCommand calls ExecuteScalar, but suppose the result is "null" if the SQL wass NULL, but it's DBNull.Value which is returned instead.

The test if (result != null) in ReliableSqlConnection.ExecuteCommand<T>(), line 327 should be replaced with, at least, if (result != null && result != DBNull.Value) to handle real null results.

comments

styx31 wrote Apr 26, 2013 at 9:44 AM

Here is a unit test which should work :
[TestMethod]
public void TestExecuteSimpleCommandWithNullResult()
{
    SqlCommand command = new SqlCommand("select cast(null as int)");
    int? result = connection.ExecuteCommand<int?>(command);

    Assert.IsNull(result);
}