Search code examples
c#nhibernatemappingcomposite

NHibernate - How to map a table with multiple foreign keys to its corresponding classes?


I have the following tables :

enter image description here

Basically, a user is part of a project and has certain access rights on that particular project.

I created the following entities:

  1. User
  2. Project
  3. AccessRight

How can I map, using NHibernate, a User entity so that I can easily fetch the access rights per project he's assigned to ?

I was thinking of doing the following:

  1. Create a new entity called "ProjectRight" which will have a Project ID as the primary key
  2. Create a "Many-To-Many" set within the User entity :

    public virtual ICollection<ProjectRight> ProjectRights { get; set; }

    And in the User mapping:

<set name="ProjectRights" table="Users_Projects_Rights">
  <key column="id_UserGroup"></key>
  <many-to-many class="ProjectRight" >
    <column name="id_Project" />
    <column name="id_AccessRight" />
  </many-to-many>
 </set>

Would this work ? And if yes, does that mean that I'll need to create two additional entities so that I can map the Projects and AccessRights table..?

Thanks


Solution

  • I'd suggest creating ProjectRight as a component instead of an entity:

    <set name="ProjectRights" table="Users_Projects_Rights">
        <key column="id_User"/>
        <composite-element class="ProjectRight">
            <many-to-one name="Project" column="id_Project"/>
            <many-to-one name="Right" column="id_AccessRight"/>
        </composite-element>
    </set>
    

    This is one of the two ways suggested by the NHibernate documentation. For the other one see here.