fluentsprings / ExpressMapper

Mapping .Net types
http://www.expressmapper.org
Other
310 stars 65 forks source link

Inheritance mapping #122

Closed philippe-lavoie closed 7 years ago

philippe-lavoie commented 7 years ago

I'm mapping classes from one namespace to another. I found out really fast that inheritance mapping is an issue raised a long time ago, without a resolution (yet). So I tried to be a good little coder and added my custom mapping

    public class ChoiceMapper :
        ICustomTypeMapper<Contracts.Models.FakeOrder.Choice, Contracts.Models.FakeRestaurant.Choice>
    {
        public Contracts.Models.FakeRestaurant.Choice Map(IMappingContext<Contracts.Models.FakeOrder.Choice, Contracts.Models.FakeRestaurant.Choice> context)
        {
            switch (context.Source.GetType().Name)
            {
                case "Choice":
                    return Mapper.Map<Contracts.Models.FakeOrder.Choice, Contracts.Models.FakeRestaurant.Choice>(context.Source);
                case "ComplexChoice":
                    return Mapper.Map<Contracts.Models.FakeOrder.ComplexChoice, Contracts.Models.FakeRestaurant.Choice>((Contracts.Models.FakeOrder.ComplexChoice)context.Source);
                default:
                    throw new ArgumentException(nameof(context) + " is not of a valid type");
            }
        }
    }

For obvious reasons, the above throws a stack overflow. In essence, what I naively tried to do was, given a type Choice, check if it's the base or the derived class then map using the normal mapper strategy.

I'm sure I'm not the first that need to map derived types that are complex, what is their approach? If the approach is to write 'by hand' mapping, then the point of an object to object mapper is kinda lost...

anisimovyuriy commented 7 years ago

Dear @philippe-lavoie,

Since 1.9.0 - Expressmapper supports inheritance. Just really short example:


Mapper.Register<Source, Destination>()
                      .Include<SubSource, SubDestination>();

I'll update documentation shortly!

Thanks for the request!