-->

How do I translate complex objects in ServiceStack

2020-06-06 00:57发布

问题:

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?

回答1:

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.



回答2:

You are going to have to handle complex mapping explicitly yourself. Here are some unit tests from ServiceStack src that show how complex types are currently handled.

You can see that the the Car object is serialized into JSON.

var user = new User() {
    FirstName = "Demis",
    LastName = "Bellot",
    Car = new Car() { Name = "BMW X6", Age = 3 }
};

var userDto = user.TranslateTo<UserDto>();

Assert.That(userDto.FirstName, Is.EqualTo(user.FirstName));
Assert.That(userDto.LastName, Is.EqualTo(user.LastName));
Assert.That(userDto.Car, Is.EqualTo("{Name:BMW X6,Age:3}"));

I agree with Trust Me - I'm a Doctor that Automapper is worth using. The built in Translating was designed to reduce dependencies.