Home > Enterprise >  AutoMapper - How do you map from Class<T> to Class<T> using ctor?
AutoMapper - How do you map from Class<T> to Class<T> using ctor?

Time:01-10

I need to map from Class<T> to Class<T> using a constructor. Even though it is a direct mapping, except whatever T is, I cannot use an empty ctor here since I need to force explicit instantiations to use the ctor params.

The dest is always null so genericTypes will throw.

CreateMap(typeof(Request<>), typeof(Request<>))
            .ConvertUsing((src, dest, context) =>
            {
                var mapFromRequest = src.GetType();
                var userId = (string)mapFromRequest.GetProperty("UserId", typeof(string)).GetValue(src) ?? throw new ArgumentException("UserId has no value");
                var requestId = (string)mapFromRequest.GetProperty("RequestId", typeof(string)).GetValue(src) ?? throw new ArgumentException("RequestId has no value");

                var genericTypes = dest.GetType().GetGenericArguments();
                var destination = typeof(Request<>).MakeGenericType(genericTypes);
                var mapToRequest = Activator.CreateInstance(destination, new RequestContext(userId, requestId));
                return mapToRequest;
            });

CodePudding user response:

ForCtorParam was the solution here.

CreateMap(typeof(Request<>), typeof(Request<>))
            .ForCtorParam("requestContext", opt => opt.MapFrom((src, context) =>
            {
                var mapFromRequest = src.GetType();
                var userId = (string)mapFromRequest.GetProperty("UserId", typeof(string)).GetValue(src) ?? throw new ArgumentException("UserId has no value");
                var requestId = (string)mapFromRequest.GetProperty("RequestId", typeof(string)).GetValue(src) ?? throw new ArgumentException("RequestId has no value");

                return new RequestContext(userId, requestId);
            }));

CodePudding user response:

You don't need reflection with AM. Try smth like:

CreateMap(typeof(Request<>), typeof(Request<>))
            .ForCtorParam("requestContext", opt => opt.MapFrom(src => src));
CreateMap(typeof(Request<>), typeof(RequestContext));
  • Related