2

how can i map a Collection of Objects to a single object of an concrete type using automapper?

Sample:

Model:

public class SystemOptionsModel
{
    public string OptionID { get; set; }
    public string OptionValue { get; set; }
}

DTO:

public class SystemOptionsDto
{
    public  Deliverymode? Deliverymode { get; set; }
}

I tried to map ICollection of SystemOptionsModel to one SystemOptionsDto with the following mapping configuration:

 CreateMap<SystemOptionsModel, SystemOptionsDto>()
           .ForMember(dest => dest.Deliverymode, o =>
           {

               o.Condition((src) => { return src.OptionID.Trim().ToLower().Equals("someString"); });
               o.MapFrom(srs => (Deliverymode)Enum.Parse(typeof(Deliverymode), srs.OptionValue.Trim()));
           });

As result I get a list of DTOs with one Item for each Item in the Source Collection.

i also tried this:

CreateMap<SystemOptionsModel, SystemOptionsDto>()
           .ForMember(dest => dest.Deliverymode, o =>
           {
               o.MapFrom(src => src.OptionID.Trim().ToLower().Equals("someString") ? (Deliverymode?)Enum.Parse(typeof(Deliverymode), src.OptionValue.Trim()) : null);
           });

The result is also a List of SystemOptionsDto and not a single SystemOptionsDto.

macostobu
  • 832
  • 7
  • 12

1 Answers1

1

From explanation it doesn't clear how values should be converted if collection contains more than one item with OptionID equal to "someValue". Maybe it's impossible. Solution is:

cfg.CreateMap<ICollection<SystemOptionsModel>, SystemOptionsDto>()
    .ForMember(dest => dest.Deliverymode, opt => opt.ResolveUsing(
        src => src.Where(i => i.OptionID.Trim().ToLower() == "someString")
                    .Select(option => (Deliverymode?)Enum.Parse(typeof(Deliverymode), option.OptionValue.Trim()))
                    .FirstOrDefault()));
Valerii
  • 2,147
  • 2
  • 13
  • 27