Automatic matching of complex objects

I am using Automapper to map model objects to DTOs. In a DTO, the primary key must be replaced with the corresponding object. I used the following code for this:

// 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))));


But when I go from SubDepartment to SubDepartmentDTO in my controller, the "Department" object is always null. I tried replacing the code _departmentRepository.GetById(sd.DepartmentId.Value)

with a hardcoded Department object and it works well. I have also confirmed that there is a corresponding department in the database for the primary key. Can anyone point out what I am doing wrong?


source to share

1 answer

Try with this code

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


if it doesn't work you can try Custom value resolver

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




All Articles