Jean-Paul Boodhoo's post on MappingEnumerable<T> reminds me how DTOs sometimes require an inordinate amount of effort for the simple jobs they perform. You need to define them, instantiate them, map them, groom them, and take them for walks twice a day. It always felt to me that the language should help to reduce the DTO tax, somehow.
In JP's post, he is using the following interface to define a mapper responsible for transforming domain objects into data transfer objects (screen bound DTOs, I'm assuming).
public interface IMapper<Input, Output>
{
Output MapFrom(Input input);
}
Where a simple implementation might look like:
public class DepartmentMapper : IMapper<Department, DepartmentDisplayItemDTO>
{
public DepartmentDisplayItemDTO MapFrom(Department input)
{
return new DepartmentDisplayItemDTO()
{
ID = input.ID,
Name = input.Name
};
}
}
LINQ takes some of the grunge work out of mapping DTOs. For example, if you aren't injecting a mapping strategy at runtime, LINQ can transform a Department object into a Department DTO in place:
IEnumerable<Department> departments = departmentRepository.GetAllDepartments();
return
from d in departments
select new DepartmentDisplayItemDTO() { ID = d.ID, Name = d.Name };
Alternatively, when there is a mapper in play for more convoluted mapping logic:
IEnumerable<Department> departments = departmentRepository.GetAllDepartments();
return
from d in departments
select departmentDisplayItemDTOMapper.MapFrom(d);
... which is equivalent to:
IEnumerable<Department> departments = departmentRepository.GetAllDepartments();
return departments.Select(d => departmentDisplayItemDTOMapper.MapFrom(d));
I think LINQ eliminates the need for JP's MappingEnumerable<T> (a DTO tax), while keeping the advantage of deferred execution (an item isn't mapped until it is enumerated).