11

I have the following dto object:

public class PriceDto
{
   public string Ticker {get; set;}
   public double Open {get; set;}
   public double Close {get; set;}
}

The source objects:

public class RemoteData
{
   public Security Security { get; set; }
   public IList<Prices> Prices{ get; set; }
}

public class Security
{
   public string Ticker {get; set;}
}

public class Prices
{
    public double Open {get; set;}
    public double Close {get; set;}
}

In result, I want to get collection of PriceDto objects. I know how to map Ticker property. But, I have no idea how to map Prices correctly:

CreateMap<RemoteData, PriceDto>()
    .ForMember(d => d.Ticker, opt => opt.MapFrom(s => s.Security.Ticker));

Also, Automapper can't find the configuration because I have single RemoteData, but I want to get IList<PriceDto>:

var json = await rangeUrl.GetJsonAsync<RemoteData>();
var dtos = _mapper.Map<IList<PriceDto>>(json);

For the workaround, I created map from Prices to PriceDto instead of RemoteData and then just use foreach to assign Ticker. But, I want to undertand how to do it with automapper.

1

1 Answer 1

12

A good approach for this case is to use the .ConvertUsing.

...
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<RemoteData, List<PriceDto>>()
                    .ConvertUsing(source => source.Prices?.Select(p => new PriceDto
                        {
                            Ticker = source.Security?.Ticker,
                            Open = p.Open,
                            Close = p.Close
                        }).ToList()
                    );
            });
...

For more information read about custom type converters.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, probably custom converter is the best for this task. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.