chris carter's web log

Home |  Contact |  Admin
 

Active Record From Scratch

Posted on August 29, 2008

According to Martin Fowler, the Active Record pattern is described like this:

An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.

So I set out to implement this pattern in a quick spike. With no thought to performance, good coding, etc, I came up with a working Active Record implementation.

I started with the model.  I used the greatly abused concept of a blog and created a Post model with two properties, and it looks like this:

public class Post {
  public string Title { get; set; }
  public DateTime CreateDate { get; set; }
}
1
2
3
4

Notice how there's no id property.  I'm noticing that, recently anyway, all of the primary keys I define are identity columns, so I wanted to remove any concept of id from the models and keep that as something for a  base class to define and manage.

I'm heavily influenced by Castle's ActiveRecord, so of course I have a base class named ActiveRecord that takes a model as a generic type parameter, the shell of the class looks like this:

public class ActiveRecord<T> where T : new(){
}
1
2

One of the things I was thinking was that it would be nice to also have a mechanism that allowed the creation of the schema from the model, similar to how Rails works.

Here's the source code file for my naive ActiveRecord implementation.

I couldn't help but constantly thinking about how much work would be involved in defining relationships and the corresponding tables from code, maybe that'll be my next attempt.

Here's how you define an ActiveRecord class:

public class Post : ActiveRecord<Post> {
  public string Title { get; set; }
  public DateTime CreateDate { get; set; }
}
1
2
3
4