NHibernate多对多 - 如何从连接表中检索属性并将其与子项关联?

时间:2010-10-26 14:19:56

标签: nhibernate nhibernate-mapping

我在SQL中存在多对多关系,通过NHibernate映射到我的业务实体。

我想为子项添加一个属性(下面的类别),该属性仅适用于父项和子项之间的关系。在SQL中,我会在连接表中添加一个字段。

如何使用NHibernate从连接表中提取该值并将其与子属性相关联?

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  namespace="MyProject.Core.Entities"
  assembly="MyProject.Core">

  <class name="Product" table="Products" lazy="false">

    <id name="ProductId" access="field">
      <generator class="native" />
    </id>

    <property name="ProductName" access="field" />

    <idbag name="Categories" table="ProductCategory">
      <collection-id column="ProductCategoryId" type="int">
        <generator class="native" />                
      </collection-id>
      <key column="ProductId" />
      <many-to-many column="CategoryId" class="Category" />
    </idbag>

  </class>
</hibernate-mapping>

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  namespace="MyProject.Core.Entities"
  assembly="MyProject.Core">

  <class name="Category" table="Categories" lazy="false">

    <id name="CategoryId" access="field">
      <generator class="native" />
    </id>

    <property name="CategoryName" access="field" />

  </class>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:2)

基本答案是你必须声明你的连接表并为它创建一个类。类似的问题可以在这里找到:

How to use NHibernate ManyToMany with properties (columns) on Join Table (Fluent NHibernate)

根据评论澄清:

Product one-to-many ProductCategory
Category one-to-many ProductCategory
ProductCategory many-to-one Product
ProductCategory many-to-one Category