Geeks With Blogs

News Google

Nick Harrison Blog<Nick>.Next()

Following a Data Transfer Pattern, you are often faced with having to convert a list of Entities to a list of Data Transfer Objects (DTO).

A common strategy is to provide a GetDto() method in the base class for the Entities. This leads to a conversion process similar to:


foreach (var entity in ListOfEntities)






While this works it is a little clutzy and cumbersome, especially considering the alternative.


This can be converted to a LINQ expression as



var ListOfDTOs = ListOfEntities.Select(entity => entity.GetDto()).ToList();



But what about going the other way around? We don't really want to define a GetEntity method in the DTO. This can potentially lead to cyclic dependencies, and we don't want to have any logic in the DTO itself.


This is actually a great place for an extension method even though we are dealing with a class that we wrote. Consider an Extension method like this:



public static TEntity GetEntity<TEntity, TDto>(this TDto data)

where TEntity : EntityBase<TDto >, new()


TEntity returnValue = new TEntity();

MapProperties(data, returnValue);

return returnValue;




The MapProperties method handles a reflective property mapper.


With such an extension method, we can now write logic similar to this:



ListOfEntities = (from dto in ListOfDTOs

select dto.GetEntity<SampleEntity, SampleDto>()).ToList();

Posted on Friday, July 9, 2010 3:16 PM | Back to top

Comments on this post: Snazzy Syntax for Converting a List of Entities to a List of Dtos

# re: Snazzy Syntax for Converting a List of Entities to a List of Dtos
Requesting Gravatar...
I prefer to define an implicit cast on the dto class. Then I can just do


If you have a service method that returns a single entity dto you don't even need to specify the cast:

public EntityDto GetFirstOne()
return entities.First();
Left by Ryan on Jul 09, 2010 3:42 PM

comments powered by Disqus

Copyright © Nick Harrison | Powered by: