无法使用自动映射器返回列表

时间:2019-11-19 04:06:00

标签: c# automapper

我有一个将名字和姓氏结合在一起的视图模型

public class EmployeeDTO
{
    public string emp_id { get; set; }
    public string fullname{ get; set; }

    public List<EmployeeDTO> EmployeeDTOMap(List<employeeinfo> entities)
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.ValidateInlineMaps = false;
            cfg.CreateMap<employeeinfo, EmployeeDTO>()
                .ForMember(d => d.emp_id, o => o.MapFrom(src => src.emp_id))
                .ForMember(d => d.fullname,
                    o => o.MapFrom(src => string.Format("{0} {1}", src.firstname, src.lastname)))
                .ForAllOtherMembers(o => o.MapAtRuntime());
        });

        var mapper = config.CreateMapper();
        var dest = mapper.Map(mapper.Map(entities, typeof(List<employeeinfo>)), new List<EmployeeDTO>());
        return dest;
    }

}

但唯一的问题是,尽管我传递了2个实体EmployeeDTOMap(),但返回值仍为空。

1 个答案:

答案 0 :(得分:0)

为什么需要自动映射器?

public class EmployeeDTO
{
    public string emp_id { get; set; }
    public string fullname { get; set; }

    public List<EmployeeDTO> EmployeeDTOMap(List<employeeinfo> entities)
    {
        return entities.Select(o => new EmployeeDTO
        {
            emp_id = o.emp_id,
            fullname = string.Format("{0} {1}", o.firstname, o.lastname)
        }).ToList();
    }

}