开发者

Adding audit columns to a Fluent NHibernate many-to-many junction table

开发者 https://www.devze.com 2023-01-22 00:26 出处:网络
I\'m using Fluent NHibernate to generate a database schema from .Net entity classes. I have two classes User and Permission wi开发者_StackOverflowth a many to many relationship, and Fluent NHibernate

I'm using Fluent NHibernate to generate a database schema from .Net entity classes. I have two classes User and Permission wi开发者_StackOverflowth 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消