我们在另一个类中有一个类作为需要使用 Automapper 映射的属性。我们编写了一个解析器,它将源类属性映射到destinationMember 属性。我写了下面的逻辑,它不起作用。
我们收到以下错误。
错误映射类型。
映射类型:SubscriberDTO -> Subscriber ConsoleAutomapperTestHarness.SubscriberDTO -> ConsoleAutomapperTestHarness.Subscriber
类型映射配置:SubscriberDTO -> Subscriber ConsoleAutomapperTestHarness.SubscriberDTO -> ConsoleAutomapperTestHarness.Subscriber
属性:订阅者设置
using AutoMapper; //5.1.1.0
using System;
namespace ConsoleAutomapperTestHarness
{
public class Program
{
public static void Main(string[] args)
{
SubscriberDTO subDTO = new SubscriberDTO();
subDTO.AllowAddPFA = true;
subDTO.AllowAutoPay = true; ;
subDTO.SubscriberID = 10000;
subDTO.FirstName = "Kishor";
new SubscriberAutoMapper();
Subscriber sub = Mapper.Map<SubscriberDTO, Subscriber>(subDTO);
Console.WriteLine(sub.SubscriberSettings.AllowAddPFA.ToString());
Console.ReadLine();
}
}
public class SubscriberAutoMapper
{
public SubscriberAutoMapper()
{
Mapper.Initialize(cfg => {
cfg.CreateMap<SubscriberDTO, Subscriber>()
.ForMember(dest => dest.SubscriberSettings, opt => opt.ResolveUsing<SubscriberAutoMapperResolver>());
});
Mapper.AssertConfigurationIsValid();
}
}
public class SubscriberAutoMapperResolver : IValueResolver<SubscriberDTO, Subscriber, Settings>
{
public Settings Resolve(SubscriberDTO source, Subscriber destination, Settings destMember, ResolutionContext context)
{
//line which is working.
return new Settings() { AllowAddPFA = source.AllowAddPFA };
//line which is not working
// var result = context.Mapper.Map<SubscriberDTO, Settings>(source);
// var result = Mapper.Map<SubscriberDTO, Settings>(source);
//var result = Mapper.Map<SubscriberDTO, Settings>(source,destMember);
//var result = context.Mapper.Map<SubscriberDTO, Settings>(source, destMember, context);
//return result;
}
}
public class Subscriber
{
public int SubscriberID { get; set; }
public Settings SubscriberSettings { get; set; }
public string FirstName { get; set; }
}
public class Settings
{
public bool AllowEnrollment { get; set; }
public bool AllowAutoPay { get; set; }
public bool AllowAddPFA { get; set; }
}
public class SubscriberDTO
{
public int SubscriberID { get; set; }
public string FirstName { get; set; }
public bool AllowEnrollment { get; set; }
public bool AllowAutoPay { get; set; }
public bool AllowAddPFA { get; set; }
}
}