How to map classes in NHibernate using Roles or Composition

Created : 7/11/2022

Question

I believe this is a common question / problem but have not been able to find a good clean concise answer.

The Problem

How to map entities that appear to have an inheritance relationship:

Company
  Supplier
  Manufacturer
  Customer

However, a Supplier can be a Manufacturer.

or

Person
  Doctor
  Patient
  Employee

Where a Patient can be a Doctor or can be an Employee.

Suggestion: Use Roles

In discussions on the NHibernate forums, the response is often that this is multiple inheritance.

http://forum.hibernate.org/viewtopic.php?t=959076

They solution suggested is to use composition or to use "Roles". However, I cannot find any examples or explanation on how exactly to do that.

"Favor composition over inheritance." Remember that little goodie from class? In this instance I have to agree that you are trying multiple inheritance-- not possible in C# or Java (yet). I, personally, would encourage you to think about re-modeling so you have a Person object and a person has a one-to-many collection of Roles.

Questioned by : quip

Answer

You probably want to consider using the Roles. So a Role will have a set of Persons. Or a Person will have a set of Roles or both. This would probably imply that there is an Association class that maps persons to roles.

Define a Person class with all properties that are common to people. Then define a Role super class and DoctorRole, PatientRole and EmployeeRole sub classes (Assuming that each role has different properties).

The Person class can have a Collection of roles defined and the Role class can have a Collection of people defined. Or it might be easier to create an Association class, lets call it PeopleRole.

This page explains how to do the mapping so that PeopleRole is a composite element. Look at the Order/Product/LineItem example. Your Person is like Order, PeopleRole is like LineItem and Role is like Product.

Answered by : Vincent Ramdhanie