简体   繁体   中英

Map two variables in one destination from one source with Automapper

I have want to map two destinations with automapper from the same source variable. It is a DateTime that should be mapped to both interview_start and interview_end.

This is my current code:

CreateMap<FromModel, ToModel>()
.ForMember(dest =>
     dest.interview_start,
     opt => opt.MapFrom(src => src.created_at))
.ForMember(dest =>
    dest.interview_end,
    opt => opt.MapFrom(src => src.created_at));

What I would like that are written in the same function. As it is easier to understand that those two properties share the same source variable. They are mapped from the same property and it makes the code more readable.

CreateMap<FromModel, ToModel>()
.ForMember(dest =>
     (dest.interview_start, dest.interview_end),
     opt => opt.MapFrom(src => src.created_at))

Do anyone know of a better way to map two variables from one variable?

If you really want to do something like this (I personally don't see any issue with readability of first example), you could come close to what you are looking for with an extension method two effectively wrap two calls to the ForMember :

public static class AutomapperExtensions
{
    public static IMappingExpression<TSource, TDestination> ForTwoMembers<TSource, TDestination, TMember>(this IMappingExpression<TSource, TDestination>  mappingExpression, Expression<Func<TDestination, TMember>> destinationMember1, Expression<Func<TDestination, TMember>> destinationMember2, Action<IMemberConfigurationExpression<TSource, TDestination, TMember>> memberOptions)
    {
        return mappingExpression
            .ForMember(destinationMember1, memberOptions)
            .ForMember(destinationMember2, memberOptions);
    }
}

Your code would end up looking like:

CreateMap<FromModel, ToModel>()
.ForTwoMembers(dest1 => dest1.interview_start, dest2 => dest2.interview_end,
     opt => opt.MapFrom(src => src.created_at))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM