Object / Object mapping

time to read 1 min | 124 words

Fairly often, we need to do some sort of a transformation between one object to another. It is usually across layers, such as when we want to turn an entity to a DTO (for sending on the wire of for UI purposes).

Here is the overall pattern to solve such a task. I did try to make it into a framework, but even I can't make it more complex than this.

public class OrderToOrderDTO 
	public delegate void Transformer(Order o, OrderDTO d);
	List<Transformer> transforms = new List<Transformer>()
		(y, z) => z.ID = y.Id, 
		(x,z) => z.CustomerName = x.Name

	public OrderDTO Transform(Order k)
		OrderDTO t = new OrderDTO();
		transforms.ForEach((item) => item(k, t));
		return t;