I have been battling a severe case of eye strain the past couple of weeks which has limited my ability to blog. I have constrained myself to four hours on the PC per day over the last couple of weeks to allow my eyes to recuperate.
As mentioned earlier, I had been reading Applying Domain-Driven Design and Patterns With Examples in C# and .NET by Jimmy Nilsson. Sadly I still haven't read past Chapter 8 due to my visual inadequacies, but this hasn't stopped me from thinking about domain-driven design and from doing a little side programming.
Lately I have been thinking about the Active Record Design Pattern, which is a respectable domain model implementation that looks at persistence as a responsibility rather than a service. As put by Fowler, Active Record is
- An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.
Typically with Active Record you will see persistence instance methods, like Save, Delete and possibly Update, on the domain objects as well as static finder methods, like FetchByID and FetchBy[FK].
As with all domain layer implementations, the choice of implementing Active Record is usually based on a particular domain model. Active Record is often ideal when you have a 1:1 relationship between domain objects and database tables and little need for a data mapper. There are also very few business rules other than simple validation, making "separation of concerns" not so important because the domain objects exist mainly to be displayed and to be persisted. In essence, we are often talking about forms-over-data applications which make up most of the web applications today.

Layer Supertype
Most Active Record implementations introduce a Layer Supertype, which is a fancy word for a base class. As put by Fowler, Layer Supertype is
- A type that acts as a supertype for all types in its layer
Essentially, there is a lot of common / redundant functionality that will end up in these Active Record Domain Objects that needs to be refactored ( pulled up ) to a base class. A lot of this is state tracking ( IsNew, IsDirty, IsDeleted ), child-parent synchronization, and persistence methods.
Code Generation and Frameworks
Active Record solutions can be found everywhere, so if you find yourself coding these domain model implementations by hand you are behind the times :) For .NET, you can find Active Record solutions using O/R Mappers like .netTiers, LLBLGen Pro, WilsonORMapper, and XPO to name a few. Those frameworks are not necessarily limited to Active Record, but they do have implementations to the best of my knowledge. Given an existing database, you can find yourself with a generated Active Record implementation in a couple of minutes using such tools.
Castle Project's ActiveRecord
Another implementation of Active Record that I stumbled upon the other day is Castle Project's ActiveRecord, which is an Active Record implementation that sits on top of NHibernate. ActiveRecord harnesses the power of NHibernate with a simpler API for those users who want / need a more simplified and productive form of persistence - a pretty ingenious idea at leveraging existing frameworks IMHO.
The "framework" is very addictive as I was easily able to provide CRUD and Finder functionality to business objects by adding a few attributes, a base class and minimal code to both the Global.asax and web.config files. Here is a simple tutorial:
You can find a Getting Started Guide to ActiveRecord here:
Hayden.ActiveRecord
I was so impressed by Castle Project's ActiveRecord that I decided to make my own Active Record Framework for simple domain layer implementations. I shamelessly took a similar interface contract ( API ) of Castle Project's ActiveRecord and DLinq's Attributes for kicks to see how long it would take me to pull off a rudimentary, unrefactored, ad-hoc prototype implementation of Active Record :)
Ten hours isn't bad for the implementation I pulled off. Given a simple business object that shares the same attribute names of TableAttribute and ColumnAttribute as used by DLinq objects and a Layer Supertype ActiveRecordBase<T> as with Castle Project's Active Record:
[Table("Posts")]
public class Post : ActiveRecordBase<Post>
{
[Column(Name="PostId",Id=true,AutoGen=true)]
public int Id
{
get { return _id; }
set { _id = value; }
}
[Column]
public string Title
{
get { return _title; }
set { _title = value; }
}
[Column]
public string Description
{
get { return _description; }
set { _description = value; }
}
}
Using Hayden.ActiveRecord :) one can experience a set of static Finder Methods as such without writing any code:

Here are some possibilities:
// Fetch Post with Primary Key = 1
Post post = Post.FetchByID(1);
// Fetch All Posts Ordered By Title
Post[] posts = Post.FetchAll(Order.Asc("Title"));
// Fetch All Posts in Category 1
Post[] posts = Post.FetchAll(Expression.Eq("CategoryId",1));
or
Post[] posts = Post.FetchAllByProperty("CategoryId",1);
or
Post[] posts = Post.FetchAll(Expression.Eq("CategoryId",1), Order.Desc("PublishedDate"));
Again, I shamlessly used an API similar to Castle Project's ActiveRecord. I assume Castle Project's implementation uses NHibernate's query language, whereas I built a very rudimentary engine ( actually, engine is giving my implementation too much credit ) from scratch, but as of yet won't handle complex queries. All of the queries above refer to class members and not table columns to keep you from thinking about the database.
Of course, with all Active Record implementations you will need to implement instance members to Save, Update and Delete instances. I haven't implemented object state tracking as of yet, so I exposed a public Update Method so that one could explicitly tell the Active Record implementation that this instance was originally pulled from persistent storage. Naieve I know, but what can you expect from a few hours:

Attributes and Reflection
I used attributes to specify the mapping of business objects to database tables. I used DLinq's implmentation so that I can use DLinq's generators like SqlMetal and DLinq Designer to generate my classes. A couple other O/R Mappers that use attributes are NPersist and Retina.NET.
If you are looking for a tutorial on using custom attributes and reflection to pull off mapping like this, I wrote a short tutorial on this:
Not wanting to do too much reflection in real-time, I added a singleton, called DataContext ( yep, took the name from DLinq ), that is inititalized from say Global.asax with a list of types. During this initialization process I create the mapping files that are used in real-time to speeds things up. A call would look like this:
DataContext.Instance.Initialize(new Type[] { typeof(Post) });
I haven't completed it yet, but I like the idea as done by Castle Project where you can specify an assembly where I assume it will iterate through the types that implement the custom attributes. I will add that functionality as well as the reading of DLinq's XML Mapping File.
Conclusion
Active Record is a very useful domain model implementation for forms-over-data applications. Embrace it when it makes sense and leverage all the wonderful frameworks that exist. Microsoft Linq for SQL and ADO.NET Entity Data Model will be an interesting addition to all of this and may make these types of domain models easier to implement.
Active Record Resources:
Posted
Fri, Jun 16 2006 9:37 PM
by
David Hayden