Search code examples
nhibernatefluent-nhibernatenhibernate-mappingautomapping

Mapping person and employee in Fluent NHibernate


How can I map following queries using Fluent NHibernate (entity, mapping class etc..), the employee ids are stored in identifier tables. Person table contains employee information and non-employee information.

SELECT p.Id, p.FirstName, p.LastName

 FROM Person p  

UNION ALL

SELECT e.Id, e.FirstName, e.LastName 

  FROM Employee e 

INNER JOIN identifier i on (e.Id = i.value)

INNER JOIN type t on (i.typeid = t.id and i.typeName = 'EmployeeId')

Anyone?


Solution

  • You need to use a union strategy for mapping your subclasses. Have a read of the subclassing section of the Fluent NHibernate wiki, but instead of calling DiscriminateSubclassesOnColumn in your ClassMap you'd call UseUnionSubclassForInheritanceMapping.

    What you'd end up with is a ClassMap for your base-class, then a SubclassMap for each of your subclasses; the ClassMap would have a call to UseUnionSubclassForInheritanceMapping in it's constructor.

    Something like this:

    public class PersonMap : ClassMap<Person>
    {
      public PersonMap()
      {
         // ... mappings ...
         UseUnionSubclassForInheritanceMapping();
      }
    }
    
    public class EmployeeMap : SubclassMap<Employee>
    {
      public EmployeeMap()
      {
        // ... mappings ...
      }
    }