When using calling the SqlCommand.ExecuteReader()
method, ReSharper tells me I have a possible NullReference exception when I use the SqlDataReader object afterwards.
So with the following code:
using (SqlConnection connection = GetConnection())
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = ; //snip
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//snip
}
}
}
}
The while (reader.Read())
line is underlined.
My question is when would the reader object ever be null? I've never come across it and the documentation doesn't mention that it could be. Should I be checking if it's null or is it safe to ignore?
And why would ReSharper think that it could be null, when for example it lets me use the SqlCommand without recommending it be checked for null? I'm guess there's an attribute on the ExecuteReader method.
I have determined one reason why ExecuteReader() can return null.
In the case where I was getting a null, I had sent my client a script to update a stored procedure. My client's Sql Server (2000) is set up so that DB users need a permission to execute a stored procedure. When they updated the SP the permission was removed and not re-assigned. In this instance the SqlCommand.ExecuteReader() returned a null.
Re-assigning the permission fixed this.
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