Wednesday, February 07, 2007

Finding database model information in Castle and ActiveRecord

Since this is my first post on the subject, let me introduce the Castle project - a .Net framework that I have been exploring recently. It has a project that tries to mimic ActiveRecord in Ruby-On-Rails, although the Castle version of ActiveRecord uses NHibernate. The good news is that an ActiveRecord class doesn't require any XML configuration or mapping files. The somewhat bad news is that you DO have to declare your classes and populate them with properties, private members and AR mapping attributes. Since I will probably use SQLServer 2000, I will just write a few queries to extract the data type and field list for each table that I want to support. More on this later.

For today, I wanted to extract the class-to-database mapping information that Castle's ActiveRecords feeds to NHibernate. I finally looked through the source code a bit and after a blind alley (NHibernate.Cfg Configuration is mostly for database connections), I ran across the ActiveRecordModel class. This has the primary key, properties, foreign keys, etc. associated with a particular class that inherits from ActiveRecordBase. I wanted to see how hard it would be to offer a generic grid view and/or form view without hand-coding a maintenance module for each form. It looks possible to me. Anyway, here is some C# code to dump the properties of a Blog (as defined in a tutorial on the Castle web site) ...

using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Framework.Config;
using Castle.ActiveRecord.Framework.Scopes;
using Castle.ActiveRecord.Framework.Internal;

... inside your application, after calling ActiveRecordStarter.Initialize or Register ...

// get Blog's model
ActiveRecordModel blogModel = ActiveRecordModel.GetModel(typeof(Blog));
foreach (PropertyModel prop in blogModel.Properties)
Debug.WriteLine(prop.Property.Name + " is a " + prop.Property.PropertyType.Name);

Labels: , , , ,


Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home