我正在尝试将一个实体对象映射到不同的视图模型。我有一个基本视图模型和两个从基础派生的视图模型。视图模型是通过工厂方法在运行时根据其类型属性创建的。派生视图模型没有单独的实体,源实体具有派生视图模型的所有属性。问题是Automapper能够通过工厂方法创建正确的对象,但派生对象中的属性根本不会映射。仅映射基本视图模型的属性。
示例实体:
public class VehicleEntity
{
public int Type { get; set; }
public int LoadCapacity { get; set; }
public TrailerEntity Trailer { get; set; }
}
public class TrailerEntity
{
public int Capacity { get; set; }
}
查看模型:
public class VehicleVM
{
public int Type { get; set; }
}
public class CarVM: VehicleVM
{
public TrailerVM Trailer { get; set; }
}
public class TruckVM : VehicleVM
{
public int LoadCapacity { get; set; }
}
public class TrailerVM
{
public int Capacity { get; set; }
}
public static class VehicleFactory
{
public static VehicleVM GetInstance(int type)
{
switch (type)
{
case 1:
return new CarVM();
case 2:
return new TruckVM();
default:
return new VehicleVM();
}
}
}
最后映射:
List<VehicleEntity> vehicleList = new List<VehicleEntity>();
vehicleList.Add(new VehicleEntity()
{
Type = 1,
LoadCapacity = 0,
Trailer = new TrailerEntity()
{
Capacity = 120
}
});
vehicleList.Add(new VehicleEntity()
{
Type = 2,
LoadCapacity = 8000,
Trailer = null
});
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<VehicleEntity, VehicleVM>()
.ConstructUsing((Func<VehicleEntity, VehicleVM>)(rc => VehicleFactory.GetInstance(rc.Type)))
.Include<VehicleEntity, TruckVM>()
.Include<VehicleEntity, CarVM>();
cfg.CreateMap<VehicleEntity, TruckVM>();
cfg.CreateMap<VehicleEntity, CarVM>();
cfg.CreateMap<TrailerEntity, TrailerVM>();
});
IMapper mapper = config.CreateMapper();
var vehicleVMs = mapper.Map<List<Data.VehicleEntity>, List<VehicleVM>>(vehicleList);
在上面的示例中,只有Type属性映射到CarVM和TruckVM中。其他属性不是......我也尝试使用ForMember方法来映射源实体的派生类属性但没有运气。
cfg.CreateMap<VehicleEntity, TruckVM>().ForMember(dst => dst.LoadCapacity, opt => opt.MapFrom(src => src.LoadCapacity));
有可能实现这个目标吗?
答案 0 :(得分:1)
您可以使用以下配置
# netstat -alpn | grep perl
tcp 0 0 ::1:113 :::* LISTEN 1357/perl
在这种情况下, ConstructUsing 基于 Type 属性创建正确的目标对象,然后在 BeforeMap 中将源VehicleEntity实例映射到创建的目标对象。您也可以在 AfterMap 方法中执行此操作。
或者您可以在 ConstructUsing
中立即在其上创建目标对象和地图源var config = new MapperConfiguration(
cfg =>
{
cfg.CreateMap<VehicleEntity, VehicleVM>()
.ConstructUsing(rc => VehicleFactory.GetInstance(rc.Type))
.BeforeMap((s, d, c) => c.Mapper.Map(s, d));
cfg.CreateMap<VehicleEntity, TruckVM>();
cfg.CreateMap<VehicleEntity, CarVM>();
cfg.CreateMap<TrailerEntity, TrailerVM>();
});