It is common for every table to have a common set of audit tracking fields such as DateLastModified, UserIdLastModified, etc.

In our entities, this is easily supported by having these properties defined in a base class that every entity derives from.

This has always been somewhat cumbersome from a mapping perspective. Using classic hbm mapping files there is no way to inherit such details and they had to be repeated for each mapping.

One of the many benefits that Fluent NHibernate brings to the table is a much better solution to this.

We can define an AuditMapping base class and derive our mapping classes from it and not have to duplicate the mapping of common fields.

 

 

public class AuditMap<T> : ClassMap<T> where T : IEntity

{

public AuditMap()

{

Map(p => p.DateEffective);

Map(p => p.DateExpiry);

Map(p => p.DateLastModified);

Map(p => p.TypeIdModifierOrigin);

Map(p => p.UserIdLastModifier);

}

}

 

 

You just need to constrain T to require that it implements an interface common to all Entities or be derived from the base class for all entities.

 

This proves to be a nice way to standardize mapping and simplify the process of actually mapping the classes.

 

Is anyone else using any similar techniques?

posted on Friday, July 09, 2010 2:14 PM |

Comments

Gravatar
# re: Inheriting a Class Map in Fluent NHibernate
Posted by Bogdan
on 10/25/2010 1:13 PM
Actually, I'm using the same technique for mapping common properties for versioning/auditing and similar entities.

Life saver :)
Gravatar
# re: Inheriting a Class Map in Fluent NHibernate
Posted by Scott Rickman
on 6/17/2011 10:59 AM
I usually have an abstract implementation of IEntity, map this as EntityMap : ClassMap<Entity>, mapping the audit fields and Id then map other entities as CustomerMap : SubclassMap<Customer>, only mapping the additional properties of Customer. Fluent NHibernate will see that Customer inherits Entity and create the appropriate row in the Entity table and a foreign key column in the Customer table that relates to the Entity table.
Post Comment
Title *
Name *
Email
Url
Comment *