0

Is there a safer way to read from SqlDataReader.GetFieldValue, the value may be null at times.

Error

System.Data.SqlTypes.SqlNullValueException was thrown.

Code

var roles = reader.GetFieldValue<string>(reader.GetOrdinal("Roles"))

something like TryGet etc.

AppDeveloper
  • 1,816
  • 7
  • 24
  • 49
  • Have you tried tu put it in a try catch block to manage error? –  Oct 11 '19 at 09:28
  • for some reason I need to stay within the block and not jump out of it, I've to display null in the JSON output in such case, so that's why checking for null instead of catching and managing errors. – AppDeveloper Oct 11 '19 at 09:31
  • Check for null *before* trying to read – Panagiotis Kanavos Oct 11 '19 at 09:33
  • 1
    https://stackoverflow.com/questions/1772025/sql-data-reader-handling-null-column-values – Squirrel Oct 11 '19 at 09:33
  • 1
    var roles = (reader.GetOrdinal("Roles") == null) ? string.Empty : reader.GetFieldValue(reader.GetOrdinal("Roles")) – jdweng Oct 11 '19 at 09:34
  • @jdweng that's the answer. Thanls. On a side note is it fine If I use `reader.GetString` instead of `reader.GetFieldValue`, the lateral seems verbose. – AppDeveloper Oct 11 '19 at 09:39

0 Answers0