How do I translate complex objects in ServiceStack?

旧街凉风 提交于 2019-12-03 09:23:22

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!