所以我在使用automapper时遇到了这个问题。我相信我很接近,一定要错过一些东西。
我有一个包含Address类和位置类的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; }
}
我当然希望使用AutoMapper映射到Dto:
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;
}
}