30.12.08

Mapping Subclasses in NHibernate

ContactTest.TestAddContactNotes : Failed

NHibernate.MappingException: No discriminator found for Zainco.YCW.Components.Domain.ContactNote. Discriminator is needed when 'single-table-per-hierarchy' is used and a class has subclasses

at NHibernate.Mapping.SingleTableSubclass.Validate(IMapping mapping)
at NHibernate.Cfg.Configuration.Validate()
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at Zainco.YCW.Components.Utils.NHibernateHelper.get_Session() in NHibernateHelper.cs:line 13
at Zainco.YCW.Tests.ContactTest.TestAddContactNotes() in ContactTest.cs:line 94

This was due to an incorrect mapping strategy. Instead of using the table per hierarchy strategy, I resorted to using the table per subclass mapping strategy. The base table, Note, contains the elements common to my subclasses and the ContactNote maintains the association between the contact and the Note. I have a variety of Notes in the system(CommunityNotes, ParishNotes etc).

The mapping file for this strategy is:

<class name="Note" table="Note">
<
id name="Id" column="Id">
<
generator class="native"/>
</
id>
<
property name="Content"/>
<
property name="DatePublished"/>
<
joined-subclass name="ContactNote" table="ContactNote">
<
key column="NoteId"/>
<
many-to-one class="Contact" column="ContactId" name="Contact"/>
</
joined-subclass>
</
class>

No comments: