Active Record: Mapping Rewriting

time to read 1 min | 191 words

One of the really nice things about using the NHibernate / Active Record stack is that there are so many extensions points.

One of the more fun things is the ability to do runtime modifications of the mapping. Here is a simple example:

ActiveRecordStarter.ModelsCreated+=delegate(ActiveRecordModelCollection models, IConfigurationSource source)
{
    foreach (ActiveRecordModel model in models)
    {
        if(model.Type == typeof(User))
        {
            model.ActiveRecordAtt.Table = "MyUsers";
        }
    }
};

Here we are re-writing the table that the User entity will go to. We can get much more complex, since we have all the knowledge of the structure of the code and can apply things like naming convention, validation, etc. It is also a fast way to translate between database/conventions.

NHibernate has a similar concept, INamingStrategy, which can be used to some of the same purposes, but I like this approach better, since it gives me more semantic information.