Search code examples
c#nhibernatenhibernate-mappingtable-per-classunion-subclass

Why can't NHibernate use Identity in union-subclass Table per Concrete Class mapping?


Several sources state that NHibernate can not use identity with table per concrete class and union-subclasses. Is this true, and what is the exact reason behind this ?


Solution

  • It's simple. The POID must be unique across all instances of a root entity type.

    Consider the following example:

    abstract class Vehicle { ... }
    class Car : Vehicle { ... }
    class Truck : Vehicle { ... }
    

    If you were to retrieve a Vehicle whose concrete type you don't know:

    var carOrTruck = session.Get<Vehicle>(vehicleId);
    

    ...and there were both a Car and a Truck with that Id (which is possible with identity), which one would NHibernate return? (there are more complex cases, but this illustrates one possible issue)

    Therefore, for table-per-concrete-class (a pretty bad strategy if you ask me), NHibernate needs a generator that guarantees uniqueness across subclasses.