自动映射器映射属性保持为空

时间:2018-07-19 05:49:38

标签: c# automapper

似乎我无法使嵌套映射正常工作

阅读后:http://docs.automapper.org/en/stable/Nested-mappings.html应该很容易。

我有以下课程:

public class CatalogVehicle : VehicleBase
{
    public string Type { get; set; }
    public int Year { get; set; }
    public VehicleSpecification VehicleSpecification { get; set; } = new VehicleSpecification();
} //removed some properties for readability

public class VehicleSpecification
{
    public Engine Engine { get; set; } = new Engine();
    public Transmission Transmission { get; set; } = new Transmission();
    public int Co2 { get; set; }
    public int Weight { get; set; }
} //again removed some more properties (all classes)

用于映射:

CreateMap<VehicleAndQuote, CatalogVehicle>()
    .ForMember(catalogVehicle => catalogVehicle.Id,
        source => source.MapFrom(vehicleAndQuote => vehicleAndQuote.Quote.QuotationIdentifier.Trim()))
    .ForMember(catalogVehicle => catalogVehicle.Make,
        source => source.MapFrom(vehicleAndQuote => vehicleAndQuote.Vehicle.VehicleMakeName))
    .ForMember(catalogVehicle => catalogVehicle.Model,
        source => source.MapFrom(vehicleAndQuote => vehicleAndQuote.Vehicle.VehicleModelTypeName))
    .ForMember(catalogVehicle => catalogVehicle.VehicleSpecification, opt => opt.Ignore()); //removed some lines

CreateMap<VehicleAndQuote, VehicleSpecification>()
    .ForMember(vehicleSpecification => vehicleSpecification.Co2, src => src.MapFrom(vehicleAndQuote => vehicleAndQuote.Vehicle.Co2.ToSafeInt()))
    .ForMember(vehicleSpecification => vehicleSpecification.Weight, src => src.MapFrom(vehicleAndQuote => vehicleAndQuote.Vehicle.Weight.ToSafeInt()))
    .ForMember(vehicleSpecification => vehicleSpecification.Rating, opt => opt.Ignore())
    .ForMember(vehicleSpecification => vehicleSpecification.Tyres, opt => opt.Ignore()) //removed some lines as well

CreateMap<VehicleAndQuote, Engine>()
    .ForMember(engine => engine.Displacement, opt => opt.Ignore())
    .ForMember(engine => engine.Fuel, src => src.MapFrom(vehicleAndQuote => vehicleAndQuote.Vehicle.FuelType))
    .ForMember(engine => engine.Power, src => src.ResolveUsing(GetEnginePower))
    .ForMember(engine => engine.Cylinders, src => src.MapFrom(vehicleAndQuote => vehicleAndQuote.Vehicle.Cylinders));

//etc

如您所见,我忽略了某些属性,因为否则我会收到未映射的属性错误。阅读完本文后,只要映射了所有类,它就应该可以工作。

我正在调用如下方法:var vehicle = _mapper.Map<VehicleAndQuote, CatalogVehicle>(vehicleAndQuote); <=这是包含所有信息的大类

因此,从VehicleAndQuoteCatalogVehicle的映射-前几个属性可以正常工作,但是到VehicleSpecification的映射是我的问题。那将不会正确填充...

有人看到这个问题吗?

1 个答案:

答案 0 :(得分:2)

您需要为嵌套类配置映射,而不是忽略它们:

.ForMember(catalogVehicle => catalogVehicle.VehicleSpecification, src => src.MapFrom(vehicleAndQuote => vehicleAndQuote);

代替

.ForMember(catalogVehicle => catalogVehicle.VehicleSpecification, opt => opt.Ignore());

与其他映射相同