Automapper: map properties manually

前端 未结 3 1205
轻奢々
轻奢々 2021-02-07 07:11

I just started to use automapper to map DTOs<->Entities and it seems to be working great.

In some special cases I want to map only some properties and perform additio

3条回答
  •  无人及你
    2021-02-07 07:30

    You can make some projection using MapFrom method - http://automapper.readthedocs.io/en/latest/Projection.html

    Mapper.Map(source, target)
       .ForMember(m => m.Property, opt => opt.MapFrom(src => src.ChangedProperty));
    

    For example (reffering to AutoMapper documentation):

    // Model
    var calendarEvent = new CalendarEvent
        {
            Date = new DateTime(2008, 12, 15, 20, 30, 0),
            Title = "Company Holiday Party"
        };
    
    // Configure AutoMapper
    Mapper.CreateMap()
        .ForMember(dest => dest.EventDate, opt => opt.MapFrom(src => src.Date.Date))
        .ForMember(dest => dest.EventHour, opt => opt.MapFrom(src => src.Date.Hour))
        .ForMember(dest => dest.EventMinute, opt => opt.MapFrom(src => src.Date.Minute));
    

提交回复
热议问题