Automapper:如何将Lazy <tfrom>映射到TTo?</tfrom>

时间:2014-09-26 17:47:29

标签: c# automapper

我需要将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);

1 个答案:

答案 0 :(得分:0)

这是我为解决问题所做的工作。如果有人有更好的想法,请告诉我,我会将其标记为答案。

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