最终,我正在尝试从VehicleViewMOdel-> Vehicle进行映射。来源在下面列出。值得注意的是,每个类的两个属性具有不同的类型。
执行映射的代码
var newVehicle = Mapper.Map<Vehicle>(vehicleData_);
要映射的类的代码 公共类VehicleViewModel { 公共VehicleViewModel() {
}
//Fuel Economy is in L/Km
public float CityFuelEconomy {get;set;}
public float HighwayFuelEconomy {get;set;}
public float ListPrice {get;set;}
public float SoldPrice{get;set;}
[Required]
public int ModelForeignKey {get;set;}
[Required]
public int DealerForeignKey{get;set;}
public string Notes{get; set;}
public string Color{get; set;}
}
public class Vehicle
{
public Vehicle()
{
}
[Key]
public int Id {get; set;}
//Fuel Economy is in L/Km
public float CityFuelEconomy {get;set;}
public float HighwayFuelEconomy {get;set;}
public float ListPrice {get;set;}
public float SoldPrice{get;set;}
[ForeignKey("VehicleModelId")]
public virtual VehicleModels ModelForeignKey {get;set;}
[ForeignKey("VehicleDealerId")]
public virtual Dealer DealerForeignKey{get;set;}
public string Notes{get; set;}
public string Color{get; set;}
}
要处理不同类型类型的属性映射,我在自动映射器配置(startup.cs)中使用了以下“ formember”
Mapper.Initialize(config =>
{
config.CreateMap<VehicleViewModel, Vehicle>()
.ForMember(dest => dest.DealerForeignKey, opt => opt.MapFrom<DealerResolver>())
.ForMember(dest => dest.ModelForeignKey, opt => opt.MapFrom<VehicleModelResolver>()).ReverseMap();
});
提到的解析器(VehicleModelResolver和DealerResolver)仅采用source属性(在这种情况下为thype整数),并为Vehicle.ModelForeignKey和Vehicle.DealerForeignKey返回正确类型的对象
private IVehicleRepository _vehicleRepo;
public DealerResolver(IVehicleRepository vehicleRepo_)
{
_vehicleRepo = vehicleRepo_;
}
public Dealer Resolve(VehicleViewModel source, Vehicle destination, Dealer destMember, ResolutionContext context)
{
List<Dealer> dealers = _vehicleRepo.GetDealerById(source.DealerForeignKey).ToList();
return dealers.FirstOrDefault();
}
public class VehicleModelResolver : IValueResolver<VehicleViewModel, Vehicle, VehicleModels>
{
private IVehicleRepository _vehicleRepo;
public VehicleModelResolver(IVehicleRepository vehicleRepo_)
{
_vehicleRepo = vehicleRepo_;
}
public VehicleModels Resolve(VehicleViewModel source, Vehicle destination, VehicleModels destMember, ResolutionContext context)
{
List<VehicleModels> vehModels = _vehicleRepo.GetModelById(source.ModelForeignKey).ToList();
return vehModels.FirstOrDefault();
}
}
运行代码时,我看到错误消息“没有为此对象定义无参数构造函数。” 在运行时单步执行代码会发现映射对于所有属性都很好,直到VehicleViewModel.MOdelForeignKey。
关于映射VehicleViewModel.ModelForeignKey-> Vehicle.ModelForeignKey有一些我现在看不到的东西。就像我之前说的,我意识到属性是不同类型的,但是解析器应该注意这一点。有任何想法吗?
更新-对此有建议-DI配置不正确。快速制作了一段视频,详细介绍了问题及其解决方法https://youtu.be/tGU7TjDvSK8
答案 0 :(得分:0)
youtu.be/tGU7TjDvSK8
这不是我真正的答案,我只是制作了一段视频以使其变得非常清晰。 -我想感谢Lucian Bargaoanu的真正答案。