[英]Automapper - issue when mapping one type to another
我的项目可以编译并运行-在运行时不会从一种类型映射到另一种类型。 所有代码和错误消息如下所示。 有人对此有任何想法/意见吗? 提前致谢!
我的startup.cs(配置方法)中包含以下代码:-
Mapper.Initialize(config =>
{
config.CreateMap<VehicleViewModel, Vehicle>().ReverseMap();
});
在我看来,这会在VehicleViewModel和Vehicle之间创建双向映射。
VehicleViewMOdel的代码如下:-
public class 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;}
}
为了完整起见,下面列出了Vehicle的代码:-
public class 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;}
}
当执行映射时,我看到以下消息:
找到未映射的成员。 在下面查看类型和成员。 添加自定义映射表达式,忽略,添加自定义解析器或修改源/目标类型对于没有匹配的构造函数,请添加no-arg ctor,添加可选参数或映射所有构造函数参数
编辑 -根据Hien Nguyen的有用建议,我使用了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();
});
这将使用我的解析器从视图模型中获取相关ID,并检索模型所需的正确对象。 这是在DealerResolver中开展业务的代码,例如:
public Dealer Resolve(VehicleViewModel source, Vehicle destination, Dealer destMember, ResolutionContext context)
{
List<Dealer> dealers = _vehicleRepo.GetDealerById(source.DealerForeignKey).ToList();
return dealers.FirstOrDefault();
}
我对VehicleModelResolver使用了非常相似的想法。
到现在为止还挺好。
唯一的问题是,当我运行代码并尝试进行映射时,我现在一起看到了另一条错误消息:-
AutoMapper.dll内部异常System.MissingMethodException中发生了类型为'AutoMapper.AutoMapperMappingException'的异常:没有为此对象定义无参数的构造函数
您是否知道是什么原因造成的? 我genuinley认为使用'ForMember'的原始建议是正确的方法,并认为我们几乎可以解决此问题。
您的模型和视图模型具有不同类型的属性。 您可以使用ForMember来自定义属性之间的映射。
有关自定义映射属性,请参阅此内容。 如何在AutoMapper中处理自定义属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.