自动映射复杂对象

时间:2014-10-07 08:25:45

标签: c# asp.net asp.net-mvc asp.net-web-api automapper

我正在使用Automapper将我的Model对象映射到DTO。在DTO中,主键应替换为相应的对象。为此,我使用了以下代码:

// Model class
public class SubDepartment
{
    public long Id { get; set; }
    public string Name { get; set; }
    public long? DepartmentId { get; set; }
    public DateTime LastUpdated { get; set; }
}

// DTO class
public class SubDepartmentDTO
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Department Department { get; set; }
    public long EventCount { get; set; }
}

// Mapping code

 Mapper.CreateMap<Models.Event.SubDepartment, DTO.SubDepartment>().ForMember(dto => dto.Department,
                map => map.MapFrom(sd => Mapper.Map<Department, DTO.Department>(_departmentRepository.GetById(sd.DepartmentId.Value))));

但是当我从SubDepartment映射到我的控制器中的SubDepartmentDTO时,'Department'对象始终为null。我尝试用一​​个硬编码的Department对象替换_departmentRepository.GetById(sd.DepartmentId.Value)代码,它运行良好。我还验证了数据库中存在相应的主键部门。谁能指出我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试使用此代码

Mapper.CreateMap<Models.Event.SubDepartment, DTO.SubDepartment>().ForMember(dto => dto.Department,map => map.MapFrom(sd => _departmentRepository.GetById(sd.DepartmentId.Value)));

如果它不起作用,您可以尝试自定义值解析器

Models.Event.SubDepartment, DTO.SubDepartment>().ForMember(dto => dto.Department, map => map.ResolveUsing<DepartmentResolver>());

public class DepartmentResolver: ValueResolver<Models.Event.SubDepartment,DTO.SubDepartment>
{
    Reporsitory _departmentRepository;
    protected override DTO.SubDepartment ResolveCore(Models.Event.SubDepartment source)
    {
        return _departmentRepository.GetById(source.DepartmentId.Value);
    }
}