自动映射程序:如何映射Lazy<;TFrom>;至TTo
本文关键字:lt Lazy TFrom TTo gt 映射 映射程序 何映射 | 更新日期: 2023-09-27 18:24:38
我需要将Lazy<TFrom>
的列表映射到TTo
的列表。我所做的不起作用——我只得到空值。如果没有Lazy<>
包装,它可以完美地工作。我做错了什么?
// Map this list
// It's passed in as an argument and has all the data
IList<Lazy<Employee>> employees
public static IList<TTo> MapList(IList<Lazy<TFrom>> fromModel)
{
Mapper.CreateMap<Lazy<TFrom>, TTo>();// Is this needed?
return Mapper.Map<IList<Lazy<TFrom>>, IList<TTo>>(fromModel);
// This doesn't work
// return Mapper.Map<IList<TTo>>(fromModel.Select(x => x.Value));
}
// Maps the child classes
Mapper.CreateMap<Lazy<Employee>, EmployeeDTO>()
.ForMember(x => x.AccidentDTO, i => i.MapFrom(model => model.Value.GetAccident()))
.ForMember(x => x.CriticalIllnessDTO, i => i.MapFrom(model => model.Value.GetCriticalIllness()))
.ForMember(x => x.ValidationMessages, i => i.MapFrom(model => model.Value.ValidationMessages));
// Returns nulls !!!
var dataDTO = MyMapper<Lazy<Employee>, EmployeeDTO>.MapList(employees);
以下是我为解决问题所做的工作。如果有人有更好的想法,请告诉我,我会把它标记为答案。
// Get the Values of the Lazy<Employee> items and use the result for mapping
var nonLazyEmployees = employees.Select(i => i.Value).ToList();
var dataDTO = MyMapper<Employee, EmployeeDTO>.MapList(nonLazyEmployees);
public static IList<TTo> MapList(IList<Lazy<TFrom>> fromModel)
{
Mapper.CreateMap<Lazy<TFrom>, TTo>();
return Mapper.Map<IList<Lazy<TFrom>>, IList<TTo>>(fromModel);
}
// Maps the child classes
Mapper.CreateMap<Employee, EmployeeDTO>()
.ForMember(x => x.AccidentDTO, i => i.MapFrom(model => model.GetAccident()))
.ForMember(x => x.CriticalIllnessDTO, i => i.MapFrom(model => model.GetCriticalIllness()))
.ForMember(x => x.ValidationMessages, i => i.MapFrom(model => model.ValidationMessages));