Joining NHibernate classes that share a common column but don't have a foreign key
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 products table to the Disposal table on the AssetId so that my product has a Disposals collection combined by an asset. I have defined the following mapping, but NHibernate (1.2) seems to ignore the key column defined in the bag and decides to join the Product table to the Disposal ProductId table (i.e. Product.ProductId = Disposal.AssetId). I'm not sure if this is a bug, or if I am not defining it correctly, but if anyone has a way to do this, I would be very kind.
<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>
source to share
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 when exporting the schema.
You can try property-ref, not entirely 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>
source to share
Do you have your waste associated with Products?
Your schema is not unique related to product removal. A Disposal can only relate to the asset, not the product.
Your schema says Asset has many products and Asset has many Disposals. There's nothing that says Product-Specific Recycling.
source to share