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.

6
  • Have you tried tu put it in a try catch block to manage error? Commented Oct 11, 2019 at 9: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. Commented Oct 11, 2019 at 9:31
  • Check for null before trying to read Commented Oct 11, 2019 at 9:33
  • 1
    stackoverflow.com/questions/1772025/… Commented Oct 11, 2019 at 9:33
  • 1
    var roles = (reader.GetOrdinal("Roles") == null) ? string.Empty : reader.GetFieldValue<string>(reader.GetOrdinal("Roles")) Commented Oct 11, 2019 at 9:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.