使用AutoMapper进行嵌套对象映射

所以我用automapper来解决这个问题。 我相信我近在咫尺,一定会失去一些东西。

我有一个包含Address类和Position类的Employee类:

internal class Employee : IPerson
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public Address Address { get; set; }
    public Position Position { get; set; }

}

我当然想映射到Dto的使用AutoMapper:

public class EmployeeDto
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public AddressDto Address { get; set; }
    public PositionDto Position { get; set; }
}

我相信我明白我需要配置所有潜在映射:

public static void RegisterMappings()
    {
        Mapper.CreateMap<Address,  AddressDto>();
        Mapper.CreateMap<Position, PositionDto>();
        Mapper.CreateMap<Employee, EmployeeDto>();

        Mapper.AssertConfigurationIsValid();
    }

我这样称呼代码:

 public EmployeeDto GetEmployee(int personId)
    {
        EmployeeDto dto = null;
        try
        {
            var employee = _employeeDataDao.GetEmployee(personId);

            dto = Mapper.Map<Employee,EmployeeDto>(employee);

        }
        catch (Exception ex)
        {
            Logger.Error(ex, "Get Employee failed : {0}", ex.Message);
        }
        return dto;

    }

这几乎可以工作,但地址和位置项目全部为空:返回的员工已将所有数据正确存储在员工类中!

员工类地图很好。 我怎样才能得到地图和位置信息来映射?

更新我的GetEmployee呼叫

public Employee GetEmployee(int personId)
    {

        using (var connection = myconnection)
        {
            const string storedProcedure = "sproc";
            var result = connection.Query<Employee, Address, Position, Employee>(storedProcedure,
                (employee, address, position) =>
                {
                    employee.Address = address;
                    employee.Position = position;
                    return employee;
                },
                new {PersonId = personId}, splitOn: "HomeAddressLine1, PositionTitle",
                commandType: CommandType.StoredProcedure).FirstOrDefault();
            return result;
        }
    }
链接地址: http://www.djcxy.com/p/37389.html

上一篇: Nested Object Mapping with AutoMapper

下一篇: Map readonly fields with Automapper