自动映射器 -<T> <T> 如何使用 ctor 从一个类映射到另一个类?



我需要使用构造函数从Class<T>映射到Class<T>。即使它是一个直接映射,除了T是什么,我也不能在这里使用空的变量,因为我需要强制显式实例化使用变量参数。

dest总是null,所以genericTypes会抛出

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

你不需要AM的反射。试试这样写:

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

ForCtorParam是这里的解。

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

最新更新