Search code examples
c#.netautomapper

Automapper: how to map a tuple of list of objects and enum to a list


For example i have the first object which is the source

class PersonEntity
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

and the destination is

class PersonDto
{
    public string Name {get; set;}
}

and an enum

enum NameMode
{
    first,
    full
}

my mapping profile create map looks something like this

CreateMap<(PersonEntity, NameMode), PersonDto>()
      .ForMemeber(dest => desat.Name, opt => opt.MapFrom<NameCustomeResolver>()));

where depending on the passed enum value i will either combine first and last name from the source or just use first name, now the issue is that i want to use this to map a list of PersonEntity to a list of PersonDto

i tried this

List<PersonEntity> source = new List<PersonEntity>();
List<PersonDto> destination = mapper.Map<List<PersonDto>>((source, NameMode.full));

i get the exception

Missing type map configuration or unsupported mapping.

after some research i tried the following

var result = source.AsQueryable().Select(p => (p, NameMode.full)).ProjectTo<PersonDto>(mapper.ConfigurationProvider);

but this one has the syntax error

expression tree may not contain tuple literal

i just want to achieve mapping a list of PersonEntity to a list of PersonDto


Solution

  • You can try this:

    var destination = mapper.Map<List<PersonDto>>(source.Select(x => (x, NameMode.full)));
    

    This works because source.Select(x => (x, NameMode.full)) will create an enumerable of tuple (PersonEntity, NameMode), since you already have a mapping configured between (PersonEntity, NameMode) and PersonDto. Automapper will automatically handle mapping between IEnumerable<(PersonEntity, NameMode)> and IEnumerable<PersonDto>.