Updated:
所以我相信我理解你想要做什么,很抱歉我可能稍微引导你走上了错误的道路。您的流程基本上是区分源对象是什么基础设施类型,然后创建该类型的对象。您还需要了解两种不同的 Mapper 设置方式。
在代码的第一部分中,您尝试使用 Mapper 的实例进行设置,然后使用我的使用 Mapper.Map 的静态样式,我建议始终使用静态样式,以便您能够执行更多操作引入映射配置文件的动态方法。
Mapper.Initialize(cfg => cfg.AddProfile<AutomapperRules>());
var domain = Mapper.Map<Domain.ApplicationDriverEquipmentTractorDomain>(inf);
接下来,您只需引用从基础源到配置文件中的域类型的映射类型,即
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentTractorDomain>();
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentTrailerDomain>();
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentStraightTruckDomain>();
CreateMap<ApplicationDriverEquipmentInfrastructure, ApplicationDriverEquipmentCargoVanDomain>();
然后你需要做的就是打电话给你的GetEquipment
描述 ApplicationDriver 的映射中的方法,即
CreateMap<ApplicationDriver, ApplicationDriverDomain>()
.ForMember(dest => dest.Equipments, opt => opt.ResolveUsing(x => x.Equipments.Select(GetEquipment)));
private ApplicationDriverEquipmentAbstractDomain GetEquipment(ApplicationDriverEquipmentInfrastructure infrastructure)
{
switch (infrastructure.Type)
{
case "Tractor":
return Mapper.Map<ApplicationDriverEquipmentTractorDomain>(infrastructure);
case "Trailer":
return Mapper.Map<ApplicationDriverEquipmentTrailerDomain>(infrastructure);
case "StraightTruck":
return Mapper.Map<ApplicationDriverEquipmentStraightTruckDomain>(infrastructure);
case "CargoVan":
return Mapper.Map<ApplicationDriverEquipmentCargoVanDomain>(infrastructure);
}
return null;
}
用法示例:
Mapper.Initialize(cfg => cfg.AddProfile<AutomapperRules>());
var inf = new ApplicationDriverEquipmentInfrastructure()
{
CurrentMileage = "mil",
Length = "123",
Make = "ccc",
Model = "15",
Type = "Tractor",
VINNumber = "vin"
};
var driver = new ApplicationDriver()
{
Equipments = new List<ApplicationDriverEquipmentInfrastructure>() {inf}
};
var domain = Mapper.Map<ApplicationDriverDomain>(driver);