views:

32

answers:

2

Hi
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 Engine
{
}

public class GasEngine : Engine
{
}

public class ElectricEngine : Engine
{
}

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?

A: 

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

Diego Mijelshon
I know that there is no "new" modifier but suppose that this is pseudo-code.
dario-g
If you had a `new` modifier, those properties would be completely unrelated, which makes it unnecessary to add an EngineBase in Vehicle.
Diego Mijelshon
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?
dario-g
A: 

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
Ok but then I can not use lazy-loading. You can't cast _engineProxy to GasEngine, etc. :(
dario-g
Are you sure? You should be getting a proxy for the concrete type that can be cast.
Jamie Ide

related questions