automapperautomapper-6

Mapping "long" to create an object


iam trying to map just a long field coming from my url route to create a Query Object from my controller, can i use auto mapper

CreateMap(MemberList.None);

Source :-long id

Destination:-

public class GetPlanQuery : IRequest<PlanDto>
    {
        public long Id { get; }
        public GetPlanQuery(long id)
        {
            Id = id;
        }

        internal sealed class GetPlanQueryHandler : IRequestHandler<GetPlanQuery, PlanDto>
        {
           //Logic will go here
        }
    }

Map i am using is as below

CreateMap<long, GetPlanQuery>(MemberList.None);

i am getting an exception while executing as

System.ArgumentException:
needs to have a constructor with 0 args or only optional args.'

Solution

  • As Lucian correctly suggested you can achieve this kind of custom mapping by implementing ITypeConverter:

    public class LongToGetPlanQueryTypeConverter : ITypeConverter<long, GetPlanQuery>
    {
        public GetPlanQuery Convert(long source, GetPlanQuery destination, ResolutionContext context)
        {
            return new GetPlanQuery(source);
        }
    }
    

    then specify it's usage in AutoMapper configuration:

    configuration.CreateMap<long, GetPlanQuery>()
        .ConvertUsing<LongToGetPlanQueryTypeConverter>();
    

    EDIT

    Alternatively, you can just use a Func:

    configuration.CreateMap<long, GetPlanQuery>()
        .ConvertUsing(id => new GetPlanQuery(id));