nhibernate多对多映射-映射表中的其他列? [英] nhibernate many-to-many mapping - additional column in the mapping table?

查看:85
本文介绍了nhibernate多对多映射-映射表中的其他列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下映射定义:

  <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>

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

此映射生成映射表UserRoles,该表具有两列-RoleId和UserId.

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.

是否可以在nhibernate中进行操作,还是需要在此处添加其他类并将m-to-m关系更改为2个关系?[user] 1-to-m [user_role] m-to-1 [role]?

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] ?

推荐答案

您需要添加一个额外的类,例如UserRole,在代码中保留其他属性.

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

当涉及到映射时,可以将其映射为您提到的类.但我也认为可以在Role映射中将其映射为复合元素:

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>

所有属性都不能为空,因为它们已成为UserRoles表主键的一部分.有关更多信息,请参见:

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

这篇关于nhibernate多对多映射-映射表中的其他列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆