Integrating NHibernate and Active Record

time to read 1 min | 182 words

On the face of it, this is a nonsense post. What do I mean, integrating NHibernate and Active Record? Active Record is based on NHibernate, after all. What kind of integration you need? Well, sometimes you want to be able to use NHibernate entities in an Active Record project. And that tended to be very hard. (The other way was extremely easy, just tell Active Record to generate the mapping and move from there.)

A week or so ago I added support for doing it the other way around, of adding POCO NHibernate entities into the ActiveRecord model.

Here is the test:

[Test]
public void CanIntegrateNHibernateAndActiveRecord()
{
	ActiveRecordStarter.ModelsValidated += delegate
	{
		new ActiveRecordModelBuilder().CreateDummyModelFor(typeof(NHibernateClass));
	};
	ActiveRecordStarter.Initialize(
		GetConfigSource(),
		typeof(ActiveRecordClass),
		typeof(NHibernateClass));

	Recreate();

	using (TransactionScope tx = new TransactionScope())
	{
		ActiveRecordClass ar = new ActiveRecordClass();
		ar.Friend = new NHibernateClass();
		ActiveRecordMediator.Save(ar.Friend);
		ActiveRecordMediator.Save(ar);
		tx.VoteCommit();
	}

	using (TransactionScope tx = new TransactionScope())
	{
		ActiveRecordClass first = ActiveRecordMediator<ActiveRecordClass>.FindFirst();
		Assert.IsNotNull(first);
		Assert.IsNotNull(first.Friend);
	}
}

Note that I would reserve this to advance scenarios only, in most cases, it is recommended to only use a consistent approach.