NHibernate many-to-many - how to retrieve property

2019-05-17 07:15发布

问题:

I have an existing many-to-many relationship in SQL that is being mapped to my business entities via NHibernate.

I want to add a property to the child (Category below) that is only applicable to the relationship between the parent and the child. In SQL, I would add a field to the join table.

How do I use NHibernate to pull that value from the join table and associate it with a child's property?

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

The basic answer is that you have to declare your joining table and create a class for it. A similar question can be found here:

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

Clarification based on comments:

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