views:

1081

answers:

2

I have a couple of tables that I want to map to classes. The tables look like this:

Asset
---------
AssetId
AssetName

Product
---------
ProductId
ProductName
AssetId

Disposal
---------
DisposalId
AssetId
DisposalDate

Basically what I want to do is join the Product Table to the Disposal table on AssetId so that my Product has a collection of Disposals joined by asset. I have defined the following mapping but NHibernate (1.2) seems to ignore the key column defined in the bag and chooses to join the Product table to the Disposal table by ProductId (ie Product.ProductId = Disposal.AssetId). I'm not sure if this is a bug or if I'm not defining it properly but if anyone has a way to do this I'd be most greatful.

  <class name="Product" table="Product" lazy="false">
    <id name="ProductId" column="ProductId" type="int">
      <generator class="native" />
    </id>
    <property name="ProductName" column="ProductName"/>
    <bag name="Disposals" fetch="join" >
      <key column="AssetId" foreign-key="AssetId/>
      <many-to-many class="Disposal"/>
    </bag>
  </class>
+1  A: 

Have you got your Disposals mapped to Products?

Your schema doesn't unique relate a Disposal to a Product. A Disposal can only relate to an Asset, not a Product.

You schema says to me that an Asset has many Products, and an Asset has many Disposals. There's nothing that says a Disposal is for a particular product.

David Kemp
A: 

The clean way:

  <class name="Product" table="Product" lazy="false">
    <id name="ProductId" column="ProductId" type="int">
      <generator class="native" />
    </id>
    <property name="ProductName" column="ProductName"/>
    <many-to-one name name="Asset" class="Asset" column="AssetId" />
  </class>

  <class name="Asset">
    <id name="AssetId" >
      <generator class="native" />
    </id>
    <property name="AssetName" />
    <bag name="Disposals">
      <key column="AssetId" />
      <many-to-many class="Disposal" />
    </bag>
  </class>

foreign-key is used for DDL, I think it is the name of the foreign key constraint generated by schema export.

You can try property-ref, not completely sure if it works:

  <class name="Product" table="Product" lazy="false">
    <id name="ProductId" column="ProductId" type="int">
      <generator class="native" />
    </id>
    <property name="ProductName" column="ProductName"/>
    <property name="AssetId" />
    <bag name="Disposals" fetch="join" >
      <key column="AssetId" property-ref="AssetId/>
      <one-to-many class="Disposal"/>
    </bag>
  </class>
Stefan Steinegger
please look at this question http://stackoverflow.com/questions/2673352/nhibernate-executing-sql-query-without-mapping-to-an-entity
Muhammad Akhtar