views:

1195

answers:

2

hi

I have following mapping definitions:

  <class name="Role" table="Role" optimistic-lock="version" >

    <id name="Id" type="Int32" unsaved-value="0" >
      <generator class="native" />
    </id>

    <property name="RoleName" type="String(40)" not-null="true" />

    <bag name="UsersInRole" generic="true" lazy="true" cascade="all" table="UserRoles" >
      <key  column="RoleId" />
      <many-to-many column="UserId" class="SystemUser, Domain"/>
    </bag>

and

<id name="Id" type="Int32" unsaved-value="0" >
  <generator class="native" />
</id>
<property name="UserName" type="String(40)" not-null="true" unique="true" />

This mapping generates mapping table UserRoles, which has two columns - RoleId and UserId.

However, I'd like to add extra attributes to that relation - i.e. some enum values defining state of the relation as well as effective start & end dates.

Is it possible to do in nhibernate or do I need to add additional class here and change relation m-to-m into 2 relations [user] 1-to-m [user_role] m-to-1 [role] ?

+1  A: 

Add additional class.

Matt Hinze
+6  A: 

You need to add an extra class, e.g. UserRole, in code to keep the additional properties.

When it comes to mapping this can be mapped as a class as you mentioned. But I also think it can be mapped as a composite-element in the Role mapping:

<set name="UsersInRole" lazy="true" table="UserRoles" >
  <key  column="RoleId" />
  <composite-element class="UserRole">
     <many-to-one name="User" column="UserId" not-null="true"/>
     <propery name="RelationState" not-null="true"/>
     <propery name="StartDate" not-null="true"/>
     <propery name="EndDate" not-null="true"/>
  </composite-element>
</set>

All properties must be not-null, because they're become part of the primary keys of the UserRoles table. For more information see:

BengtBe
thx. i'll give it a try
Greg