在下面的automapper示例中,我将讨论一些不同类型的问题:
P
)的属性,它们本身就是类(即PContact
,Bank
)new List<Bank>()
)Wrapper
换行IDataRecord
)怎么了?
我想将IDataRecord
的实例转换为类P
的实例。
AutoMapper.Mapper.CreateMap<IDataRecord, P>()
.ConvertUsing(x => AutoMapper.Mapper.Map<Wrapper, P>(new Wrapper(x)));
AutoMapper.Mapper.CreateMap<Wrapper, P>()
.ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.GetString("Nome")))
.ForMember(dest => dest.LastName, opt => opt.MapFrom(src => src.GetString("Cognome")))
.ForMember(dest => dest.Banks,
opt => opt.ResolveUsing(src => AutoMapper.Mapper.Map<Wrapper, List<Bank>>(src)));
AutoMapper.Mapper.CreateMap<Wrapper, PContact>()
.ForMember(dest => dest.StreetAddress, opt => opt.MapFrom(src => src.GetString("Indirizzo")))
.ForMember(dest => dest.Town, opt => opt.MapFrom(src => src.GetString("Città")))
.ForMember(dest => dest.Phone, opt => opt.MapFrom(src => src.GetString("Telefono")))
AutoMapper.Mapper.CreateMap<Wrapper, List<Bank>>()
.ConvertUsing(x => new List<Bank>() { AutoMapper.Mapper.Map<Wrapper, Bank>(x) });
AutoMapper.Mapper.CreateMap<Wrapper, Bank>()
.ForMember(dest => dest.AccountNumber, opt => opt.MapFrom(src => src.GetString("NumCC")))
.ForMember(dest => dest.IBAN, opt => opt.MapFrom(src => src.GetString("IBAN")));
答案 0 :(得分:0)
问题与AutoMapper为IDataReader有自己的Mapper这一事实有关,因此需要执行以下操作
public class AutomapperTypeAdapterFactory
:ITypeAdapterFactory
{
public AutomapperTypeAdapterFactory()
{
//scan all assemblies finding Automapper Profile
var profiles = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(t => t.BaseType == typeof(Profile));
Mapper.Initialize(cfg =>
{
foreach (var item in profiles)
{
if (item.FullName != "AutoMapper.SelfProfiler`2")
cfg.AddProfile(Activator.CreateInstance(item) as Profile);
}
});
//===>>
MapperRegistry.Mappers.Remove(MapperRegistry.Mappers.FirstOrDefault(x => x is DataReaderMapper));
}
}