Common Mistakes When Using OR/M

time to read 2 min | 392 words

David Hayden has posted about the Active Record pattern, and in particular, about using Castle.ActiveRecord. In the examples, he has a class with this structure:

public class Post
{
  public int PostId;
  public int BlogId;
  public int CategoryId;
}

I think that he did it so he would have an easy time explaining it, but I feel compelled to respond to this, because this is an anti pattern that I see a lot of OR/M new comers do. You shouldn'y work with explicit Ids when you are using you objects. A Post object shouldn't know what to do with an integer called BlogId. That is the responsability of the OR/M implementation. You shouldn't bring the database structure into your domain model.

Here is how the class should look like:

public class Post
{
  public int PostId;
  public Blog Blog;
  public Category Category;
}

Working with explicit Ids means that the OR/M can do a lot less for you, since it doesn't have enough information. For instance, it cannot eagerly load the Blog object, since it doesn't know about it. All it know is that you wanted to load an integer, and that is all.