AutoMapper - 如何将复杂对象映射到更简单的模型

AutoMapper - How map complex objects to simpler model

我想要地图 Origin.CityIdOrigin.StateId 的属性 Itinerary class 到 OriginCityIdOriginStateId 属性 共 ItineraryModel class.

例如:Itinerary itinerary = Mapper.Map<Itinerary>(ItineraryModel);

我的视图模型

public class ItineraryModel : BaseModel
{
    public int OriginCityId { get; set; }
    public int OriginStateId { get; set; }
    public bool Published { get; set; }
}

我的实体

public class Itinerary : BaseEntity
{
    public City Origin { get; set; }
    public bool Published { get; set; }
}

我试过的映射

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<ItineraryModel, Itinerary>()
            .ForPath(x => x.Origin.CityId, opt => opt.MapFrom(src => src.OriginCityId))
            .ForPath(x => x.Origin.StateId, opt => opt.MapFrom(src => src.OriginStateId))
            .ReverseMap();
    }
}

我也想.ReverseMap()但是找不到正确的语法。

您需要添加两个映射才能映射到Itenerary

CreateMap<ItineraryModel, City>()
            .ForMember(city => city.CityId, expression => expression.MapFrom(itineraryModel => itineraryModel.OriginCityId))
            .ForMember(city => city.StateId, expression => expression.MapFrom(itineraryModel => itineraryModel.OriginStateId));

CreateMap<ItineraryModel, Itinerary>()
            .ForMember(itinerary => itinerary.Origin, expression => expression.MapFrom(itineraryModel => itineraryModel));

同样,如果需要,您可以手动定义反向映射。

顺便说一句 ReverseMap() 作者不推荐

https://jimmybogard.com/automapper-usage-guidelines/