Castle ActiveRecord - Active Record Pattern Built on NHibernate - ASP.NET C#

Castle ActiveRecord - Active Record Pattern Built on NHibernate - Rapid Application Development

by David Hayden ( Sarasota Web Development )

Filed: ADO.NET, ASP.NET, Design Patterns, Web Development

 

Over the past couple of days I have been discussing the Acive Record Design Pattern for use in one's Domain Layer.

 

Per Martin Fowler POEAA, Active Record in “An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.“

Active Record is used with a domain model approach to developing your application and best used when there is a 1:1 relationship between domain objects and database tables and few business rules / complexity such that the addition of the persistence methods on the objects don't cause a distraction. With ActiveRecord, the main purpose of the domain objects is normally display ( forms-over-data applications ) and persistence to a database. Active Record has a high coupling between the business objects in the domain layer and the database, so typically one uses Active Record in those cases where there is very little chance of changing the underlying database.

When adding persistence behavior to the Active Record Objects you usually incur redundant ADO.NET Code. One will definitely want a SQL Helper Class like the Enterprise Library 2.0 Data Access Application Block to ease the burden of having to refactor the ADO.NET plumbing yourself. You will also want to introduce a Layer Supertype ( base class ) to pull up the common functionality and code that is consistent from business object to business object.

 

Castle Project's ActiveRecord

Castle Project's ActiveRecord is a unique rapid application development Active Record implementation built on top of NHibernate. From the Castle Project:

“ActiveRecord is an implementation of the ActiveRecord pattern for .Net built on top of NHibernate, without all the XML mapping of using Nhibernate directly. An ActiveRecord instance represents a row in the database, and the static methods act on all rows.”

ActiveRecord removes much of the burden of NHibernate for applications that need a simple implementation of NHibernate for their applications.

 

ActiveRecord and Blogging Engine

If we go back to my example of using Castle Project's ActiveRecord for use in making a blogging engine for a website, we only need to do a few things to get up and running quickly:

  1. Download the latest version of Castle Project's ActiveRecord
  2. Create a new website in Visual Studio
  3. Reference Castle.ActiveRecord.dll
  4. Add Web.Config Information
  5. Add Global.asax Information
  6. Create a Business Object
  7. Begin Using Your Business Object

 

Download Castle Project ActiveRecord

You can download the latest version of ActiveRecord here and create a new website in Visual Studio and reference the assembly Castle.ActiveRecord.dll from your download files.

 

ActiveRecord Web.Config Information

You will need to add some information to your Web.Config for ActiveRecord.

 

<configSections>
    <section name="activeRecord" type="Castle.ActiveRecord.
Framework.Config.ActiveRecordSectionHandler,
Castle.ActiveRecord
"/> configSections> <appSettings/> <activeRecord isWeb="true"> <config> <add key="hibernate.connection.driver class"
value="NHibernate.Driver.SqlClientDriver"/> <add key="hibernate.dialect"
value="NHibernate.Dialect.MsSql2000Dialect"/> <add key="hibernate.connection.provider"
value="NHibernate.Connection.DriverConnectionProvider"/> <add key="hibernate.connection.connection_string"
value="Data Source=.;Initial Catalog=Blog;Integrated
Security=True
"/> <config> <activeRecord>

 

In this case I am using ActiveRecord with a SQL Server 2000 Server and a database, called “Blog“, that contains the tables.

 

ActiveRecord Global.asax Settings

Add a couple of lines to your Global.asax file that specifies your ActiveRecord configuration information is in web.config and where the business objects are located that map to the database tables:

 

void Application_Start(object sender, EventArgs e) 
{
    Castle.ActiveRecord.Framework.IConfigurationSource source
= System.Configuration.ConfigurationManager.
GetSection(
"activeRecord") as Castle.ActiveRecord.
Framework.IConfigurationSource; Castle.ActiveRecord.ActiveRecordStarter.Initialize(
typeof(Post).Assembly, source); }

 

Above I am specifying that CastleRecord should look into the same assembly as the Post Class for all ActiveRecord Business Objects. In my case for the demo, Post is sitting in the AppCode Folder.

 

Create an ActiveRecord Business Object

We need to decorate the ActiveRecord Business Object with attributes that map to a database table and columns. Here is a partial description of the Post Class that maps to a Posts Table in the database.

 

/// 
/// Summary description for Post
/// 
[ActiveRecord("Posts")]
public class Article : ActiveRecordBase<Post>
{
    private int _id;

    [PrimaryKey(PrimaryKeyType.Native, "PostId")]
    public int Id
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }

    private int _blogId;

    [Property]
    public int BlogId
    {
        get
        {
            return _blogId;
        }
        set
        {
            _blogId = value;
        }
    }

    private int _categoryId;

    [Property]
    public int CategoryId
    {
        get
        {
            return _categoryId;
        }
        set
        {
            _categoryId = value;
        }
    }

    private string _title = string.Empty;

    [Property]
    public string Title
    {
        get
        {
            return _title;
        }
        set
        {
            _title = value;
        }
    }

    private string _description = string.Empty;

    [Property]
    public string Description
    {
        get
        {
            return _description;
        }
        set
        {
            _description = value;
        }
    }
}

 

Persist and Load ActiveRecord Objects

I won't go into every conceivable method on the ActiveRecordBase Class, but suffice to say that using Post is a no-brainer when it comes to using CRUD methods on the business objects. We can create a save a blog post as simple as:

 

Post post = new Post();

post.BlogId = 1;
post.CategoryId = 2;
post.Title = "Test";
post.Description = "This is a test.";

// Didn't need to write this.
// Provided by ActiveRecordBase
post.Save();

 

We can load a post by PostId (primary key) like this:

 

// Finds PostId = 2
Post post = Post.Find(2);

 

Get top 25 posts for BlogId = 1 sorted by PublishedDate:

 

Article[] articles = Article.FindAll(new ICriterion[]
{ Expression.Eq(
"BlogId", 0) }, new Order[]
{ Order.Desc(
"PublishedDate") }, 0, 25);

 

Conclusion

Not only is the Active Record Design Pattern extremely useful and intuitive for applications that are mainly forms-over-data applications, but Castle Project's ActiveRecord implementation packages all the benefits of Nhibernate in a nice Rapid Application Development Package that makes Active Record easy to implement.

Source: David Hayden ( Sarasota Web Development )

Filed: ADO.NET, ASP.NET, Design Patterns, Web Development

 

posted on Monday, June 12, 2006 12:15 PM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices