Let’s say I have a custom class like this one:
public class Customer
{
public int CustomerID { get; set; }
public string CompanyName { get; set; }
public string BusinessAddress { get; set; }
public string Phone { get; set; }
public int ParentID { get; set; }
}
I create custom objects from the database using a datareader. Ex:
while (dr.Read())
{
listCustomers.Add(new Customer(
Convert.ToInt32(dr["CustomerID"]),
Convert.ToString(dr["CompanyName"]),
Convert.ToString(dr["BusinessAddress"]),
Convert.ToString(dr["Phone"]),
Convert.ToInt32(dr["ParentID"]),
)
ParentID can be null in the database (and I can’t change it). When it’s null, the conversion obviously fails.
How should I handle null values retrieved from the DB to populate my business objects? Would it be good pratice to use Nullable Types in my custom class? Any other tips?
Absolutely. Nullable types are perfectly fine. Otherwise, you’d have to come up with some stupid convention a-la “when ParentID is -1, this means that
Customerhas no parent”. Nullable types enforce this “by design”: if there’s no parent,ParentIDwill benull.As for hydrating your objects, consider using ORM tools (such as NHibernate or BLToolkit), since you don’t really want to spend 50% of your development tine writing SQL queries and populating your objects from a data reader