Search code examples
nhibernatenhibernate-mapping

NHIbernate: Mapping Audit user


On every object in my DB, I have audit fields for CreatedBy, CreatedOn, ModifiedOn, and ModifiedBy. the CreatedBy and ModifiedBy map to a User object that I have created to map to my users table. I was originally storing the UserId (Primary key) in those fields and everything mapped fine with a mapping definition of <many-to-one name="CreatedBy" column="CreatedBy" lazy="proxy"></many-to-one>.

However, I want to switch those fields to store the username instead but I can't find how to load the persistent User entity from the non-primary-key field. I've looked into IUserTypes, ICompositeUserType, event listeners, and some other random things, but I can't seem to get anything completely working.

As of right now I've added a CreatedByName and ModifiedByName field that stores the username while the original fields still store the ID (did this when playing around with CompositeUserType), so I have both ID and username that I can utilize if needed.

This seems like something that should be common enough that there should be a solution, but I can't find anything.


Solution

  • You can specify the property-ref attribute in your many-to-one to specify an arbitrary join property.

    http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-manytoone