Tuesday, September 9, 2008

VS2008 Repository Factory Confused...

When using the VS2008 Repository Factory to build a Data layer recently, I noticed that one of the generated repository classes wasn't compiling and this baffled me greatly.

(NOTE: For those of you that don't know the Repository Factory, unfortunately I'm not going to go into much detail in this post. Rather see codeplex for further details on the VS2005 version, and here regarding the VS2008 version. )

The following generated code was throwing a wobbly on "CastDBNull", as it seemed the factory didn't generate such a method.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using Microsoft.Practices.Repository;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.SqlClient;


namespace Community.Service.WCF.DataAccess.BusinessEntities.UserRepositoryArtifacts
{
///
/// Construct a User object from OUT and IN/OUT parameters.
///

internal sealed class GetISOCommunityUserByUserGCNFactory : ISimpleDomainObjectFactory
{
public User Construct(Database db, DbCommand command)
{
User user = new User();

user.IsFollowMeEnabled= CastDBNull.To<Boolean>(db.GetParameterValue(command, "IsFollowMeEnabled") , false);

return user;
}
}
}

When you look at the above code, its obvious its trying to handle scenarios where your database returns DBNull and where your business entity doesn't.

To fix this, I decided to implement my own "CastDBNull" method, so I goolged the method name and found a few usefull blogs on the topic, with one more notable than others due to its simplicity (see http://petesbloggerama.blogspot.com/2006/12/it-aint-null-until-i-say-its-null.html)

public static class CastDBNull
{
public static T To <> (object value, T defaultValue)
{
return (value != DBNull.Value) ? (T)value : defaultValue;
}
}

Thats all for now folks!

1 comment:

New Media Labs said...

Good post Rogues! We should also blog about that problem we had with the T4 template.