3
votes

I'm using Fluent NHibernate to generate a database schema from .Net entity classes. I have two classes User and Permission with a many to many relationship, and Fluent NHibernate is correctly generating a junction table UsersToPermissions in the database.

As expected the junction table is storing the primary keys UserId and PermissionId. What I am wanting is to also have auditing information attached to this table such as CreatedDate and UpdatedDate. I have already implemented this on the non junction tables using interceptors as described in the NHibernate documentation.

How can I implement audit columns on the UsersToPermissions table?

1

1 Answers

5
votes

It's not possible directly, because relationships don't have properties.

The easiest way is to map the junction table as an entity, and project the sides using LINQ-to-objects for ease of use.

For example, assuming we call the intermediate entity UserPermission:

class User
{
    // Real relationship, mapped as bag or set with one-to-many UserPermission
    protected virtual ICollection<UserPermission> UserPermissions { get; set; }

    public virtual IEnumerable<Permission> Permissions
    {
        get { return from up in UserPermissions select up.Permission; }
    }

    public void Add(Permission permission)
    {
        UserPermissions.Add(new UserPermission
                            {
                                User = this,
                                Permission = permission
                            });
    }
}

Permission can have exactly the same if needed.