源类:
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 => ?????)
;
}
答案 0 :(得分:1)
您只需创建一个从Driver
到Pair<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()))