2

I have an class with two collections of different unrelated types

public class Entity
{
    ICollection<Foo> Foos { get; set; }
    ICollection<Bar> Bars { get; set; }
}

I want to map this using AutoMapper to another class with one collection

public class DTO {
    ICollection<FooBar>
}

I configure the mappings respectivitly for the two entity types into the Dto type.

.CreateMap<Foo, FooBar>()
.CreateMap<Bar, FooBar>()

How can I configure the mapping Entity -> Dto so that the two collections Foos and Bars is merged into Foobars?

If I configure them seperatly as this

.CreateMap<Entity, Dto>()
    .ForMember(dest => dest.FooBars, opt => opt.MapFrom(src => src.Foos))
    .ForMember(dest => dest.FooBars, opt => opt.MapFrom(src => src.Bars))

FooBars is set twice and hence overwritten by the second collection.

The question Automapper - Multi object source and one destination show ways to merge the two collections inte one in different ways, all of them requires multiple method calls when doing the actual mapping. I want to configure this so I can do the mapping by simply writing

AutoMapper.Mapper.Map<Entity, Dto>(entities);
Ulrik
  • 546
  • 1
  • 5
  • 21

1 Answers1

3

That you need is a custom value resolver:

public class CustomResolver : IValueResolver<Source, Destination, int>
{
    public int Resolve(Entity entity
        , DTO dto
        , ICollection<FooBar> fooBars
        , ResolutionContext context)
    {
        // Here you should convert from entity Foos and Bars
        // to ICollection<FooBar> and concat them.
    }
}

Then at the setup of AutoMapper you should use the above custom resolver:

// other code
.CreateMap<Entity, Dto>()
.ForMember(dest => dest.FooBars, opt => opt.ResolveUsing<CustomResolver>());
Christos
  • 53,228
  • 8
  • 76
  • 108
  • 1
    When you say **Here you should convert from entity Foos and Bars** do you mean manually or is there a way to use the mapping configuration to map the objects ? I cant figure out how to do a AutoMapper.Mapper.Map(entities); from within a custom resolver. – Linda Lawton - DaImTo Jun 04 '21 at 11:15
  • 1
    @DaImTo I mean manually. I am not aware, if we can use the mapping configuration to map the objects. – Christos Jun 05 '21 at 07:54