Ulrik
Ulrik

Reputation: 556

Mapping unrelated collections into one

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);

Upvotes: 2

Views: 570

Answers (1)

Christos
Christos

Reputation: 53958

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>());

Upvotes: 3

Related Questions