2014-09-26 76 views
0

我需要將Lazy<TFrom>的列表映射到TTo的列表。我所做的不起作用 - 我只能得到空值。沒有Lazy<>包裝它完美的作品。我究竟做錯了什麼?Automapper:如何將Lazy <TFrom>映射到TTo?

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

你可以包含設置'員工'的代碼,既有和沒有'懶'?可能你正在通過「延遲」調用的(延遲)時間丟失某些東西。 – 2014-09-26 17:56:36

+0

看起來這個博客文章可能有一些答案給你,如果你可以閱讀它通過所有可怕的格式。 http://softwareprojectmusings.blogspot.com/2010/07/custom-resolvers-for-automapper-to-use.html – 2014-09-26 18:00:24

+0

@MikeGuthrie ...它作爲參數傳遞幷包含所有數據。 – 2014-09-26 18:05:58

回答

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