How do I translate complex objects in ServiceStack?

后端 未结 2 922
醉话见心
醉话见心 2021-02-10 09:22

Suppose I have two objects:

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

and

2条回答
  •  爱一瞬间的悲伤
    2021-02-10 10:04

    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(),
            Items = from.Items.Map(x => x.ConvertTo()).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.

提交回复
热议问题