scmbgx
scmbgx

Reputation: 81

Nhibernate: How create a <bag> on two classes for same class child?

I have a class/table named "Comment"

<class name="Comment">
<id name="Id">
  <generator class="guid"/>
</id>
<property name="ReferenceId" index="Comment_ReferenceId_Index" />
<property name="Contents" length="1024" />

And I need to create a bag of comments on several other classes like Contract

<class name="Contract">
<id name="Id">
  <generator class="guid"/>
</id>
<property name="Status"/>    
<bag name="Comments">
  <key column="ReferenceId" />
  <one-to-many class="Comment" />
</bag>

Or Application:

<class name="Application">
<id name="Id">
  <generator class="guid"/>
</id>
<property name="Status" />
<bag name="Comments">
  <key column="ReferenceId" />
  <one-to-many class="Comment" />
</bag>

But this mapping give me only one foreign key, how can i create the collection to have comments on several classes?

Upvotes: 0

Views: 481

Answers (2)

scmbgx
scmbgx

Reputation: 81

The answer was:

Set the name of the foreign key to "none" and then hibernate don't create the FK but tracks the references.

<class name="Contract">
<id name="Id">
  <generator class="guid" />
</id>
<property name="Status" />    
<bag name="Comments">
  <key column="ReferenceId" foreign-key="none"/>
  <one-to-many class="Comment" />
</bag>

Upvotes: 1

NOtherDev
NOtherDev

Reputation: 9672

With this mapping you get one foreign key because you've explicitly configured it this way. <key column="..."> is the same ReferenceId column for both parent classes, this means that NHibernate is trying to make ReferenceId foreign key to both Application and Contract and this can't be done.

The easiest way is to give your key columns different names like ContractId and ApplicationId.

If you're trying to have a single ReferenceId column that will reference either Contract or Application and never both of them, you have to add discriminator column to your Contract and do <any> mapping - see this article.

Upvotes: 0

Related Questions