0

I have abstract class Vehicle and two classes that derive from: Car and ForkLift.

public abstract class Vehicle
{
    public EngineBase Engine { get; set; } 
}

public class Car : Vehicle
{
    public GasEngine Engine { get; set; }
}

public class ForkLift : Vehicle
{
    public ElectricEngine Engine { get; set; }
}

and Engine clasess:

public abstract class EngineBase
{
}

public class GasEngine : EngineBase
{
}

public class ElectricEngine : EngineBase
{
}

Engines are mapped with "table per class hierarchy". With Vehicles I want to use the same pattern.

How to map Engine class and derived with that Engine property?

How to do it with lazy-loading?

dariol
  • 1,959
  • 17
  • 26

2 Answers2

0

That code does not compile, which makes it improbable that you can map it.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • I know that there is no "new" modifier but suppose that this is pseudo-code. – dariol Jun 09 '10 at 21:22
  • If you had a `new` modifier, those properties would be completely unrelated, which makes it unnecessary to add an EngineBase in Vehicle. – Diego Mijelshon Jun 09 '10 at 23:37
  • That is true but Engine have common properties which I can show on list with all Vehicle's. How to change classes to achieve that? – dariol Jun 10 '10 at 11:04
0

Use a protected field in Vehicle and map it with an access strategy:

public abstract class Vehicle
{
    protected Engine _engine;
}

In Fluent NHibernate this would be mapped:

References(x => x.Engine, "EngineId").Access.CamelCaseField(Prefix.Underscore);

Then the classes that extend Vehicle can cast it as needed:

public class Car : Vehicle
{
    public GasEngine
    {
        get { return (GasEngine)_engine; }
        set { _engine = Value; }
    }
}
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • Ok but then I can not use lazy-loading. You can't cast _engineProxy to GasEngine, etc. :( – dariol Jun 10 '10 at 14:39
  • Are you sure? You should be getting a proxy for the concrete type that can be cast. – Jamie Ide Jun 10 '10 at 14:48
  • I am having the same problem. The proxy entity I get back is just a proxy of the base class, and can't be cast to the derived class. This doesn't make any sense to me, but it's true. It seems to go completely against what NHibernate should be doing for you. I have to use a non-lazy mapping to get it to work. – Scott Whitlock Jun 28 '11 at 13:03