Active Record: Mapping Rewriting
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.
Comments
I used a similar trick with NHibernate to insert test data into a read-only table for testing.
http://www.jameskovacs.com/blog/TestingImmutableEntitiesWithNHibernate.aspx
The extensibility and flexibility of NHibernate and Active Record are amazing.
When you say we can apply naming conventions or validation do you mean that we could have classes declared
public class MyClass {
[Property]
public string MyProperty { get; set; }
}
And apply a convention that column names all start with a type, so override the property declaration as if it were declared
[Property("strMyProperty")]
Also, what would be a use case for validations here?
Thanks
Validation - that your domain model is matching the requirements. For instance, that all the entities override equals / get hash code.
And yes, those are the naming convention I am talking about.
Comment preview