NHibernate many-to-many - how to get a property from a join table and associate it with a child?

I have an existing many-to-many relationship in SQL that maps to my business objects through NHibernate.

I want to add a property to a child (Category below), which applies only to the relationship between parent and child. In SQL, I would add a field to the connection table.

How do I use NHibernate to pull this value from the join table and associate it with a child 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>
+3
source share
1 answer

The main answer is that you must declare your join table and create a class for it. A similar question can be found here:

NHibernate ManyToMany () Join (Fluent NHibernate)

:

Product one-to-many ProductCategory
Category one-to-many ProductCategory
ProductCategory many-to-one Product
ProductCategory many-to-one Category
+2

Source: https://habr.com/ru/post/1771511/


All Articles