3

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.

Alex
  • 11,479
  • 6
  • 28
  • 50
  • http://ayende.com/blog/3941/nhibernate-mapping-inheritance this may help – wiero Feb 28 '12 at 09:57
  • unfortunately this just describes the various inheritance strategies without answering my question. Thanks anyway :) – Alex Feb 29 '12 at 06:38

2 Answers2

1

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).

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • Thanks for the post on your blog, it has explained me some things. Regarding my question - Thanks for the using a view suggestion, which I've totally forgot about and probably would be the solution for the case. In either case I've been ready to give up on the lazy loading of this 3 particular relations. – Alex Feb 29 '12 at 07:00
0

I think this post on the nhibernate.info blog does what you are looking to do.

http://nhibernate.info/blog/2011/02/16/get-load-polymorphism-in-nhibernate-3.html

If not it might give you an idea.

Frédéric
  • 9,364
  • 3
  • 62
  • 112
David McLean
  • 1,462
  • 1
  • 12
  • 27
  • I've read this article in the past and couldn't do much with it's information. Thanks anyway. – Alex Feb 29 '12 at 06:40