3

I'm using Automapper (6.2.1) for convert a hierarchy of Entity objects:

class Entity1 {}
class Entity2 : Entity1 {}
class Entity3 : Entity1 {}

To a corresponding hierarchy of DTO objects:

class EntityDTO1 {}
class EntityDTO2 : EntityDTO1 {}
class EntityDTO3 : EntityDTO1 {}

I have mapped all the convertions like this:

 CreateMap<Entity1, EntityDTO1>();
 CreateMap<Entity2, EntityDTO2>();
 CreateMap<Entity3, EntityDTO3>();

Every time I create one Entity and one DTO i will need to add a new CreateMap call to my configuration file.

There isn't a more compact method for do this?

Pippi
  • 313
  • 1
  • 4
  • 18

1 Answers1

2

If you use name conventions you can do something like this:

 AutoMapper.Mapper.Initialize(map =>
            {
                var asmEntities = Assembly.Load("DomainLibrary");
                var asmDtos = Assembly.Load("ViewModelsLibrary");

                foreach (Type entity in asmEntities.GetTypes())
                {
                    var vm = asmDtos.GetTypes().FirstOrDefault(x => x.Name == $"{entity.Name}Vm");
                    if (vm != null)
                    {
                        map.CreateMap(entity, vm).ReverseMap();
                    }
                }
}

  //  exemple names: 

Entity = Product
ViewModel = ProductVm

and this is a method which I use to get the entity dynamic:

 public static object GetEntity(object model)
        {
            var map = AutoMapper.Mapper
                .Configuration
                .GetAllTypeMaps()
                .FirstOrDefault(x => x.SourceType == model.GetType());

            if (map == null) return null;

            return AutoMapper.Mapper
                .Map(model, model.GetType(), map.DestinationType);

        }
Lucian Bumb
  • 2,821
  • 5
  • 26
  • 39