fluentsprings / ExpressMapper

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

Derivates in a collection are not mapped #79

Open sstudenik opened 8 years ago

sstudenik commented 8 years ago

The mapper does not consider the type of each source item when mapping a generic collection. It always tries to instantiate the generic destination parameter type regardless of the actual source item type.

A workaround is a custom type mapper (see below). But i think the mapper should provide a better default handling. (Propably i missed something?)

void MyMethod()
{  
       Player player = new Player()
       {
            Forename = "Peter",
            Name = "Brown",
            PlayerNumber = 15
       };

    List<Person> persons = new List<Person>()
        {
            player
        };

        // throws MissingMethodException due to abstract base class 'Person'
        List<Person> clonedPersons = Mapper.Map(persons, new List<Person>());
}

abstract class Person
{
    public String Name { get; set; }
    public String Forename { get; set; }
}

class Player : Person
{
    public int PlayerNumber { get; set; }
}

Workaraound with custom mapper:

    class PersonMapper : ICustomTypeMapper<Person, Person>
    {
        public Person Map(IMappingContext<Person, Person> context)
        {
            if (context.Source is Player)
            {
                context.Destination = new Player()
                {
                    Forename = context.Source.Forename,
                    Name = context.Source.Name,
                    PlayerNumber = ((Player) context.Source).PlayerNumber
                };
                return context.Destination;
            }
            throw new NotSupportedException();
        }
    }
anisimovyuriy commented 8 years ago

Dear @sstudenik,

I appreciate your input and help - I completely support your idea! These changes that you are talking about are coming very soon as second point in the of priority list to implement. (Support of hierarchies and interfaces).