nhibernate many-to-many mapping - additional column in the mapping table?

社会主义新天地 提交于 2019-12-17 18:25:08

问题


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:


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:

  • Nhibernate Composite Element Mapping
  • 7.2. Collections of dependent objects



回答2:


Add additional class.



来源:https://stackoverflow.com/questions/889513/nhibernate-many-to-many-mapping-additional-column-in-the-mapping-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!