November 29 2011

NHibernate - Map Umbraco member profile properties with Custom Interceptor

I'm writing an application that uses NHibernate as the data layer, but is required to integrate with an existing Umbraco system. Specifically, I have a User class that needs to map to an Umbraco member.

Using NHibernate to get the member id and email was simple enough, I just mapped my User class to the Umbraco cmsMember table like so:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("cmsMember");
        Id(x => x.Id).Column("nodeId");
        Map(x => x.Email).Column("Email");
    }
}

The bit I got stuck on was how to get Umbraco member profile properties into my User class.

Well as it turns out it's actually quite simple with the use of an NHibernate Custom Interceptor. I just created a class that inherits from the EmptyInterceptor class and overrides the OnLoad method:

public class CustomInterceptor : EmptyInterceptor
{
    public override bool OnLoad(object entity, object id, object[] state, string[] propertyNames, global::NHibernate.Type.IType[] types)
    {
        if (entity is User)
        {
            var user = (User)entity;

            // load profile properties from umbraco
            var member = new Member(user.Id);
            user.FirstName = member.getProperty("firstName").Value.ToString();
            user.LastName = member.getProperty("lastName").Value.ToString();
        }

        return base.OnLoad(entity, id, state, propertyNames, types);
    }
}

The last thing to do is pass an instance of the CustomInterceptor class to the OpenSession method of the NHibernate ISessionFactory instance:

var session = _sessionFactory.OpenSession( new CustomInterceptor() );

Sponsored by