我能够使用以下代码将相同类型的集合组映射到单个集合。
AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
dest => dest.Drivers,
opt => opt.MapFrom(src => src.BikeDrivers.Concat(src.CarDrivers).Concat(src.TruckDrivers)));
使用上述解决方案,我能够将所有三种类型的驱动程序映射到一个集合中。我的目标对象(驱动程序)具有一个名为 DriverType 的属性,该属性有助于识别驱动程序的类型。(自行车司机/汽车司机/卡车司机)
在上面的代码中,我如何根据我添加的集合设置 DriverType 属性。
例如:我必须硬编码
驱动程序类型 = 汽车司机的汽车司机集合项驱动程序类型 = 自行车驱动程序对于自行车驱动程序集合项。
提前致谢
若要设置 DriverType 属性,必须在源对象中具有此知识。我看不到你的大局,但这可能用作示例
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var s = new Source()
{
BikeDrivers = new List<BikeDriver>() {new BikeDriver()},
CarDrivers = new List<CarDriver>() {new CarDriver()},
TruckDrivers = new List<TruckDriver>() {new TruckDriver()},
};
var d = new Destination();
AutoMapper.Mapper.CreateMap<Source, Destination>().ForMember(
dest => dest.Drivers,
opt => opt.MapFrom(src => src.BikeDrivers.Concat<IDriver>(src.CarDrivers).Concat<IDriver>(src.TruckDrivers)));
var result = AutoMapper.Mapper.Map(s, d);
}
public class Driver : IDriver
{
public string DriverType { get; set; }
}
public class Destination
{
public IEnumerable<IDriver> Drivers { get; set; }
}
public class Source
{
public IEnumerable<BikeDriver> BikeDrivers { get; set; }
public IEnumerable<CarDriver> CarDrivers { get; set; }
public IEnumerable<TruckDriver> TruckDrivers { get; set; }
}
public interface IDriver
{
string DriverType { get; set; }
}
public class BikeDriver : IDriver
{
public string DriverType
{
get { return "BikeDriver"; }
set { throw new NotImplementedException(); }
}
}
public class CarDriver : IDriver
{
public string DriverType
{
get { return "CarDriver"; }
set { throw new NotImplementedException(); }
}
}
public class TruckDriver : IDriver
{
public string DriverType
{
get { return "TruckDriver"; }
set { throw new NotImplementedException(); }
}
}
}
}