SafeDataReader returning null values?

SafeDataReader returning null values?

Old forum URL:

GaryG posted on Wednesday, March 19, 2014

I had assumed that SafeDataReader would convert any null strings coming from SQL Server into String.Empty.

But after finding some app exceptions logged, I have confirmed that null values from the database are being set to Nothing ( in their properties. I don't want to have to deal with null/Nothing in string properties.

Am I doing something wrong?

The code I am using was generated by CodeSmith, using encapsulated implementation. It uses a SafeDataReader, and in this case it passes it to a Map routine.

Something like this:

LoadProperty(_LongDescriptionProperty, reader.Item("LongDescription"))

Will break my app if I try something like:

Foo.LongDescription.Trim, because it will throw an exception.

Am I doing something wrong? I'd hate to have to write a bunch of code to check for null values, and convert them to empty strings.


FWIW, I'm a longtime user of CSLA (since VB6 days). Not on every project, but on quite a few, in different industries. It's a great tool.



JonnyBee replied on Wednesday, March 19, 2014


I would like to see more of your code and how you use SafeDataReader.

If you use reader["LongDescription"] - the method returns an object and YOUR CODE is responsible for conversion and/or null check.
If you use reader.GetString("LongDescription") - the method knows which type to return and will always return a string value (assuming the underlying DataReader correctly identifies the value as null, ie IsDBNull returns true).

This is the actual code:

public object this[string name]
    object val = _dataReader[name];
    if (DBNull.Value.Equals(val))
      return null;
      return val;

public string GetString(string name) {   return GetString(_dataReader.GetOrdinal(name)); } public virtual string GetString(int i) {   if (_dataReader.IsDBNull(i))     return string.Empty;   else     return _dataReader.GetString(i); }

GaryG replied on Wednesday, March 19, 2014

Thanks, JonnyBee. I'll test that out when I get back to my office, but I'm pretty sure that's exactly the problem.

The CodeSmith template generated code like this:

LoadProperty(_FooProperty, reader.Item("Foo"))

Instead of:

LoadProperty(_FooProperty, reader.GetString("Foo"))

Looks like I'll have to modify the CodeSmith template for this too.

fyi, I'm new to version 4.3 (coming from 2.x a few years ago), and still learning the Ins and Outs.

Thanks for the heads-up.


Copyright (c) Marimer LLC