如何翻译在ServiceStack复杂的对象? [英] How do I translate complex objects in ServiceStack?

查看:151
本文介绍了如何翻译在ServiceStack复杂的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个对象:

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

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

如果我收到一个对象 orderDTO 这是完全组装并做 orderDTO.TranslateTo<排序>()结果只会有名称填充,而不是客户产品。有没有办法做一个递归翻译或唯一的选择是将客户和每一个手动的项目?

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?

推荐答案

我将在一个可重复使用的扩展方法把这个包起来,例如:

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(),
    }
}



然后可以称为每当你需要映射到订单DTO,例如:

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

return order.ToDto();



ServiceStack的的自动映射可在维基

ServiceStack的党的路线是,如果你的映射需要比默认的常规行为是从自动映射器可推算出更多,那么你应该把它包装背后干的扩展方法,这样的扩展和您映射所需自定义设置清晰表达并易于维护的代码。这个建议在ServiceStack,例如很多东西维护联合国的常规和复杂的国际奥委会代码结合,而不是依赖于一个不起眼的重量级国际奥委会功能。

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.

如果你喜欢它,你当然可以采用第三方工具,如AutoMapper。

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

这篇关于如何翻译在ServiceStack复杂的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆