Search code examples
c#nhibernatefluent-nhibernateautomappingdiscriminator

fluent nhibernate discriminator from related table


I've the following 3 table's with example values of

Vehicles ( id = 1, type_id = 20 , ... )
Vehicle_Types ( vt_id = 20, class_id = 160, ... )
Vehicle_Classes ( vcls_id = 160, name = "Concrete1" )

I've got

public class Concrete1 : Vehicle
{

}

And I want nhibernate to instantiate an Concrete1 when loading vehicle #1 in

Vehicle /*Concrete1*/ v = session.load<Vehicle>(1);

How could I do that with automappings? Thanks in advance.

Edit1

I'm starting to think this is impossible, therefore any workaround would be appreciated. Any clue for the xml (non fluent) version might be of a great help either.


Solution

  • OK, first, the bad news.

    • You can't have the discriminator in a separate table, period. You could hack around this by using a select statement with a join as the source table, but then your entity would be effectively read-only. Or you can use a view, which could work, but delegates more work to the DB.
    • Even with correct mapping, session.load<Vehicle>(1) will never return a derived type (except if you disable lazy-loading, which is a bad idea, or if the concrete instance was already loaded as such in the session). You can get the concrete instance with this hack.

    Now, your data model looks like it would work better with a Vehicle has-a Type relationship than a <ConcreteVehicle> is-a Vehicle one.

    This gives you more flexibility (you could change the type of a vehicle, for example), and you can keep polymorphism features by using a strategy pattern (the vehicle type contains the behavior).