ReliableSqlConnection does not handle well ExecuteScalar with NULL results


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.


styx31 wrote Apr 26, 2013 at 10:44 AM

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