Paul_87
Paul_87

Reputation: 117

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?

Upvotes: 1

Views: 736

Answers (1)

Vidmantas Blazevicius
Vidmantas Blazevicius

Reputation: 4802

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))

Upvotes: 2

Related Questions