我们在另一个类中有一个类作为需要使用Automapper进行映射的属性。我们编写了一个解析器,它将源类属性映射到destinationMember属性。我写了下面的逻辑,它不起作用。
我们收到以下错误。
映射类型时出错。
映射类型:SubscriberDTO - >订户 ConsoleAutomapperTestHarness.SubscriberDTO - > ConsoleAutomapperTestHarness.Subscriber
类型地图配置:SubscriberDTO - >订户 ConsoleAutomapperTestHarness.SubscriberDTO - > ConsoleAutomapperTestHarness.Subscriber
属性:SubscriberSettings
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; }
}
}
答案 0 :(得分:4)
ValueResolver老实说看起来有点过分,你可以完全放弃它并用尽可能小的方法实现所需的结果(假设默认的AutoMapper行为使得它们在具有相同名称时显式指定属性是多余的,就像在大多数情况下一样模型基本上):
Mapper.Initialize(cfg => {
cfg.CreateMap<SubscriberDTO, Subscriber>()
.ForMember(d => d.SubscriberSettings, o => o.MapFrom(s => s));
cfg.CreateMap<SubscriberDTO, Settings>();
});