Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting from dto to polymorphic business object

Tags:

c#

dto

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:
dto

Business object:
business object

now the question is how do I convert my Order entity?
I can think of 2 possible solutions:

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

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

like image 299
J. Ed Avatar asked Dec 04 '25 16:12

J. Ed


1 Answers

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.

like image 85
Ryan Bennett Avatar answered Dec 06 '25 04:12

Ryan Bennett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!