BusinessRx Community

Dedicated to the advancement of software, technology and the people who devote their lives to it.

Welcome to BusinessRx Community Sign in | Join | Help
in Search

BusinessRx Reading List

These blog entries are written by industry experts and leaders. We consider this content to be a good read for any software developer or web technologist.

LINQ and the DTO Tax

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

Published Wednesday, December 19, 2007 11:24 PM by OdeToCode Blogs

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems
'