Automapper: map properties manually

前端 未结 3 1206
轻奢々
轻奢々 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:16

    If you just want to map only some select property than you have to do as below

    // Create a map
    var map = CreateMap<Source,Target>();
    // ingnore all existing binding of property
    map.ForAllMembers(opt => opt.Ignore());
    // than map property as following
    map.ForMember(dest => dest.prop1, opt => opt.MapFrom( src => src.prop1));
    map.ForMember(dest => dest.prop2, opt => opt.MapFrom( src => src.prop2));
    
    0 讨论(0)
  • 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<CalendarEvent, CalendarEventForm>()
        .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));
    
    0 讨论(0)
  • 2021-02-07 07:40

    If I read your question correctly, yes, as long as your destination (target) property matches your conversion.

    So if I am going from a string to a bool for a Status of "A" or "I" (active/inactive), I can do something like:

    .ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status == "A"))
    

    And then when going the other direction, convert it back:

    .ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status ? "A" : "I"))
    

    A date example:

    .ForMember(dest => dest.SomeDate, opt => opt.MapFrom(src => src.SomeDate.ToString("M/d/yyyy")));
    
    0 讨论(0)
提交回复
热议问题