DAAB Best Practices

Topics: Data Access Application Block
May 13, 2007 at 4:37 AM
Hi all,

I see that mostly, people do this when using DAAB (please tell me if anyone has better way to do this).

Database db = DatabaseFactory.CreateDatabase();
IDataReader dr = // Somecode to get the data reader stuff
Customer customer; // Some biz object
customer = new Customer(dr.GetString(0), dr.GetInt32(1), dr.GetDateTime(2));

my question is, are there better ways to do this (creating biz objects from data reader)? I used EntLib several times, and somehow in my case, if any of those column value is NULL (let's say the 2nd column, which is supposed to be converted to Int32), it'll raise an exception. How to make it gracefully ignore the NULL value and somehow fill it with default value (If the Int32 column is NULL, fill it with 0)?

Or do I have to check every single column like: dr.IsDBNull(0) ? String.Empty : dr.GetString(0) ?
May 13, 2007 at 10:18 AM
I for one quess that according to the domain driven design the responsibility to construct Customer object it's better to deligate to another object - factory class created especially for Customer. This CustomerFactory has a method like this:
public Customer GetCustomer( IDataReader dataReader )

then in a repository class you can just call like this:
Database db = DatabaseFactory.CreateDatabase( Constants.CustomerDatabaseName );
ICustomer customer = Customer.Empty;
   customer = FactoryProvider.CustomerFactory.GetCustomer( database.ExecuteReader( command ) );
catch( Exception ex )
  if( ExceptionPolicy.HandleException( ex, "DAL" ) )
return customer;

The best practice suggested by Web Service Software Factory's Data Access recipes is having seporate factories for each CRUD operation agains each entity object - like CustomerInsertFactory, CustomerUpdateFactory etc, but I think it's possible only if you rely on code generation because it requires lots of manual work creating new classes :)

May 14, 2007 at 8:19 PM
Yo dude you might want to look into using Rocky Lhotka's CSLA Framework's SafeDataReader. It implements IDatareader and each one of its .Getx methods always returns at least the default value for the relevant datatype (it already does the checking for null values and returns a corresponding default value). It totally Rocks.
May 15, 2007 at 5:55 PM
I have read several sources recommending the use of SQL Stored Procedures as a best practice for database access. By using the below syntax in your stored procedure you can normalize any NULLS into another value. I believe this is a best practice since it puts the normalization close to the data, encapsulated at the database.

ISNULL( Record.Field1, '' ) AS FirstField,
ISNULL( Record.Field2, 0 ) AS SecondField

In the above, any nulls in Field1 are replaced with an empty string ('') and any nulls in Field2 are replaced with a 0.