A Pattern for Handling Null values in .NET objects

  • Thread starter Thread starter Brendan McLoughlin
  • Start date Start date
B

Brendan McLoughlin

Hi,

I am looking for opinions and alternatives for handling
null values in a data object which reads a record from a
database table.

This object will have properties which will be populated
from the DB table columns, standard enough. But what
about the instance where a column could be null.

The strategy I have used before is to assign a known
value to a property where the DB column is null
(Integer.Minvalue for a property of type integer).
The object then knows that the property is really null
when the DB is being updated from the object,

Has anyone any better pattern for doing this, or
alternate design strategies,

Brendan
 
If you are using stored procedures you can use the isnull
() MSSql method.

isnull(name,"") as kundenr,
 
So you would essentialy replace the null value with a
default value like integer properties are assigned 0 or
Integer.minvalue and when you are going to the database
convert this back to null when adding it to the stored
procedure param list.

B.
 
Try this

When setting the object properties

If IsDBNull(Fields(i)) The
obj.Properties(i)=Nothin
Els
obj.Properties(i)=Fields(i
End I

When saving the changes to the DB
If obj.Properties(i)=Nothing The
Fields(i)=System.DBNull.Valu
Els
Fields(i)=obj.Properties(i
End I

Hope it works for you.
 
I have always tended to use 2 properties for this and populate private
variables as well. This works then for databinding also. When accessing the
value, simply test the IsNull property before retrieving the actual.

private int foreignKey = 0;
private bool foreignKeyIsNull = false;

public int ForeignKey {
get {return this.foreignKey;}
set {this.foreignKey = value;}
}

public bool ForeignKeyIsNull {
get {return this.foreignKeyIsNull;}
set {this.foreignKeyIsNull = value;}
}

private void Scatter(dataRow row) {
if (!(foreignKeyIsNull = (dataRow["ForeignKey"].Value == DBNull.Value)))
this.foreignKey = (int)dataRow[ForeignKey"].Value;
}

private void Gather(dataRow row) {
if (this.foreignKeyIsNull)
dataRow["ForeignKey"].Value = DBNull.Value;
else
dataRow["ForeignKey"].Value = this.foreignKey;
}
 
Back
Top