Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I translate complex objects in ServiceStack?

Suppose I have two objects:

class Order
{
    string Name {get; set;}
    Customer Customer {get; set;}
    Item[] Items {get; set;}
}

and

class OrderDTO
{
    string Name {get; set;}
    CustomerDTO Customer {get; set;}
    ItemDTO[] Items {get; set;}
}

If I receive an object orderDTO that is fully populated and do orderDTO.TranslateTo<Order>() the result will only have Name populated, not Customer or Items. Is there a way to do a recursive translation or the only option is to translate Customer and each of the Items manually?

like image 983
kojo Avatar asked Feb 17 '23 04:02

kojo


1 Answers

I would wrap this in a re-usable extension method, e.g:

public static OrderDTO ToDto(this Order from)
{
    return new OrderDTO { 
        Name = from.Name,
        Customer = from.ConvertTo<CustomerDTO>(),
        Items = from.Items.Map(x => x.ConvertTo<ItemDTO>()).ToArray(),
    }
}

Which can then be called whenever you need to map to an Order DTO, e.g:

return order.ToDto();

Some more examples of ServiceStack's Auto Mapping is available on the wiki.

ServiceStack's party-line is if your mapping requires more than the default conventional behavior that's inferable from an automated mapper then you should wrap it behind a DRY extension method so the extensions and customizations required by your mapping are cleanly expressed and easily maintained in code. This is recommended for many things in ServiceStack, e.g. maintain un-conventional and complex IOC binding in code rather than relying on an obscure heavy-weight IOC feature.

If you prefer it, you can of course adopt a 3rd party tool like AutoMapper.

like image 101
mythz Avatar answered Mar 04 '23 13:03

mythz