I am currently using a sql data reader (in vb.net) to extract an article object via a stored proc from a SQL Server 2008 database. Part of this object includes the two properties shown below:
theArticle.Truthfulness = ((myReader.GetInt32(myReader.GetOrdinal("Truthfulness"))))
theArticle.Relevance = ((myReader.GetInt32(myReader.GetOrdinal("Relevance"))))
My problem is that the Truthfulness and Relevance may return a null value and this is causing the function to fall over.
I think I understand why. I am asking for an integer value (getin32) and because null is returned it fails.
How do I accommodate the null value from the database so it does not fall over?
You can check whether or not a given ordinal position is null using
.IsDBNull()and then do something – e.g. set your value to -1 or something:As Mike Hofer points out in his answer, you could also wrap all this logic into an extension method:
and then just use that “SafeGetInt32” method instead:
Marc