AutoMapper:如何将对象集合映射到Pair <int,string =“”>集合

时间:2019-05-25 13:37:29

标签: c# collections automapper

源类:

public partial class Carrier 
{
    public virtual ICollection<Driver> Drivers { get => _drivers ?? (_drivers = new List<Driver>()); protected set => _drivers = value; }

其中Driver是:

public partial class Driver 
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

目的地类别:

public class CarrierDto
{
    public List<Pair<int, string>> Drivers { get; set; }

我是手动完成的:

            new CarrierDto
            {
                //...
                Drivers = p.Drivers.Select(d => new Pair<int, string> { Text = d.FirstName + " " + d.LastName, Value = d.Id }).ToList(),

如何使用Automapper映射Drivers属性?

public class AutoMapperEfCarrier : AutoMapper.Profile
{
    public AutoMapperEfCarrier()
    {
        CreateMap<Carrier, CarrierDto>()
            .ForMember(dest => dest.Drivers, opt => ?????)
            ;
    }

2 个答案:

答案 0 :(得分:1)

您只需创建一个从DriverPair<int, string>的地图:

public class AutoMapperEfCarrier : AutoMapper.Profile
{
    public AutoMapperEfCarrier()
    {
        CreateMap<Carrier, CarrierDto>(); // no need to specify Drivers mapping because the property name is the same

        // those below are just examples, use the correct mapping for your class

        // example 1: property mapping
        CreateMap<Driver, Pair<int, string>>()
            .ForMember(p => p.Value, c => c.MapFrom(s => s.Id))
            .ForMember(p => p.Text, c => c.MapFrom(s => s.FirstName + " " + s.LastName));

        // example 2: constructor mapping
        CreateMap<Driver, Pair<int, string>>()
            .ConstructUsing(d=> new Pair<int, string>(d.Id, d.LastName));
    }
}

答案 1 :(得分:-1)

我通过以下方式实现了它:

            .ForMember(dest => dest.Drivers, opt => opt.MapFrom(src => src.Drivers.Select( d=> new Pair<int, string>() { Value = d.Id, Text = $"{d.FirstName} {d.LastName}" }).ToList()))