Nested Object Mapping with AutoMapper

So I am having this issue with automapper. I believe I am close just must be missing something.

I have an Employee class that contains Address class and position class:

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

}

I would of course like to map to Dto's using 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; }
}

I believe I understand that I need to configure all prospective mappings:

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

        Mapper.AssertConfigurationIsValid();
    }

I call the code like so:

 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;

    }

and this almost works except address and position items are all null: The returned employee has all data properly stored in the employee class!

The employee class maps just fine. How can I get the address and position information to map?

UPDATE My GetEmployee Call

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/37390.html

上一篇: 复杂的自动映射器配置

下一篇: 使用AutoMapper进行嵌套对象映射