Erik Philips
Erik Philips

Reputation: 54638

Map multiple derived types

I'm trying to map multiple types, about 50 to other types (50 of them) they are 1 to one, but I want to map from a interface to a concrete type.

Relevant code example:

using AutoMapper;
using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    internal class Program
    {
        public interface IAnimalBO { }
        public interface IBearBO : IAnimalBO { }
        public interface ITigerBO : IAnimalBO { }

        public static void Main()
        {
            var config = new MapperConfiguration(cfg =>
            {
                // Base class mapping..
                cfg.CreateMap<IAnimalBO, AnimalVM>();  


                cfg.CreateMap<ITigerBO, TigerVM>();
                cfg.CreateMap<IBearBO, BearVM>();
            });

            var mapper = config.CreateMapper();

            // Configure AutoMapper

            var businessObjects = new List<IAnimalBO>
            {
                new TigerBO(),
                new BearBO()
            };

            var results = mapper.Map<IEnumerable<AnimalVM>>(businessObjects);

            foreach (var result in results)
            {
                Console.WriteLine(result.GetType().Name);
            }
            Console.ReadKey();
        }

        public class AnimalVM { }
        public class BearBO : IBearBO { }
        public class BearVM : AnimalVM { }
        public class TigerBO : ITigerBO { }
        public class TigerVM : AnimalVM { }
    }
}

The expected output should be:

TigerVM

BearVM

but the actual output is:

AnimalVM

AnimalVM

I'm not sure how to setup automapper to map these types.

If I commend the base line mapping:

                // Base class mapping..
                // cfg.CreateMap<IAnimalBO, AnimalVM>();  

then I get the following exception:

Error mapping types.

Mapping types:

List'1 -> IEnumerable'1 System.Collections.Generic.List'1[[ConsoleApplication1.Program+IAnimalBO, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IEnumerable'1[[ConsoleApplication1.Program+AnimalVM, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]

Upvotes: 0

Views: 738

Answers (1)

Win
Win

Reputation: 62290

You want to use include<> which selects the most derived mapping from a class.

More information at Mapping Inheritance.

var config = new MapperConfiguration(cfg =>
{
    // Base class mapping..
    cfg.CreateMap<IAnimalBO, AnimalVM>()
        .Include<ITigerBO, TigerVM>()
        .Include<IBearBO, BearVM>();
    cfg.CreateMap<ITigerBO, TigerVM>();
    cfg.CreateMap<IBearBO, BearVM>();
});

enter image description here

Upvotes: 3

Related Questions