How to 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 get a fully filled orderDTO and orderDTO.TranslateTo<Order>() object, the result will only have Name , not Customer or Items . Is there a way to make a recursive translation, or is the only option is to translate the client and each of them manually?

+4
source share
2 answers

I would wrap this in a reusable extension method, for example:

 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 up whenever you need to match DTO orders, for example:

 return order.ToDto(); 

A few more examples of ServiceStack Auto-matching are available on the wiki .

The ServiceStack service side is if your mapping requires more than the standard default behavior that is output from the automated mapper, then you should wrap it with the DRY extension method so that the extensions and settings needed for your mapping are clear and easy supported in code. This is recommended for many things in ServiceStack, for example. Maintain non-standard and complex IOC binding in code, rather than rely on the unclear heavy function of IOC.

If you prefer this, you can, of course, adopt a third-party tool such as AutoMapper.

+5
source

You will have to handle the complex display explicitly. Below are some unit tests from ServiceStack src that show how complex types are handled.

You can see that the Car object is being serialized in 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. Inline translation was designed to reduce dependencies.

+3
source

Source: https://habr.com/ru/post/1469219/


All Articles