Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely cast nullable result from sqlreader to int?

I have a table which contains null values and I need to get data from the table using SqlDataReader. I can't figure out how I can safely cast DBNull to int.

I'm doing it in this way at the moment:

...
reader = command.ExecuteReader();
while (reader.Read()) {
     int y = (reader["PublicationYear"] != null) ? Convert.ToInt32(reader["PublicationYear"]) : 0;
     ...
}
...

but getting a Object cannot be cast from DBNull to other types. when PublicationYear is null.

How can I get the value safely?

Thanks.

like image 297
Burjua Avatar asked Feb 21 '12 12:02

Burjua


1 Answers

You should compare reader["PublicationYear"] to DBNull.Value, not null.

like image 102
Mr Lister Avatar answered Sep 20 '22 13:09

Mr Lister