views:

25

answers:

1

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>
+2  A: 

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:

http://stackoverflow.com/questions/3937402/how-to-use-nhibernate-manytomany-with-properties-columns-on-join-table-fluent/3937498#3937498

Clarification based on comments:

Product one-to-many ProductCategory
Category one-to-many ProductCategory
ProductCategory many-to-one Product
ProductCategory many-to-one Category
Kendrick
So I'm starting to see a trend. Is it safe to say that by adding data to my many-to-many relationship I now have a one-to-many from the parent to the relationship and a many-to-one from the relationship to the child? Is the relationship a new entity as suggested in http://stackoverflow.com/questions/2713329/nhibernate-many-to-many-relationship-with-field-in-the-relationship-table?
Mayo
The relationship is a new entity. The many-to-many in NHibernate is essentially a shortcut that allows you to skip that step when you aren't including any extra data in the link. Your understanding of the relationships is correct (I've added them to the answer).
Kendrick
Well, it took some effort but it's working now. I'm thankful for loose coupling and unit tests. Thanks for the push in the right direction.
Mayo