I am using web service which receives a flat DTO representing an Order, and I have to convert my business representation of an order to this flat representation.
Here are the objects-
DTO:
Business object:
now the question is how do I convert my Order entity?
I can think of 2 possible solutions:
Have the Order know how to represent itself as a DTO: OrderDTO dto = order.ToDto();
But this has the obvious disadvantage of the business entity knowing the data representation.
Have this done by some sort of Convertor: OrderDTO dto = Convertor.Convert(order);.
But the convertor code would have to look like this:
if (order is OnlineOrder)
{
dto.Email = ((OnlineOrder)order).Email;
}
which is, of course, terrible.
Any suggestions? can automapper help here (I'm not really familiar with it)?
You are looking for a factory, which is essentially what your "Converter" is. Your code would look something like:
var factory = new OrderDTOFactory();
OrderDTO orderDTO = factory.CreateOrder(order);
Inside the factory you can impliment it a few different ways. Automapper could be useful here and is something to condsider, though your DTO isn't very large. Automapper has been most useful to me for objects with many properties that need to be transferred.
I don't think your "converter" code is really that terrible. It is easy to read, though not very extensible. However if the amount of subclasses is pretty static, then this isn't really a problem is it? I am not sure how else you could tell if your class had a specific method or not outside of more granular reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With