Data Transfer Objects - Mapping in DTO or in a Business Object?

I have a WCF service and just created a DTO for a business object.

My question is where to put the comparison between the two?

A) In the DTO?

public class PersonDTO { [DataMember] public string Id { get; set; } [DataMember] public string Name { get; set; } public void CloneFrom(Person p) { Id = p.Id; Name = p.Name; } public void Populate(Person p) { p.Id = Id; p.Name = Name; } } 

or

B) In a business object?

 public class Person { public string Id { get; set; } public string Name { get; set; } public void CloneFrom(PersonDTO dto) { Id = dto.Id; Name = dto.Name; } public PersonDTO GetDTO() { return new PersonDTO() { Id = Id; Name = Name; } } } 

I like the separation of problems in (the business object does not know DTO), but I prefer the encapsulation of B (there is no need to expose the guts of business objects in the DTO).

Just thought, is there a standard way?

+6
source share
3 answers

I would think that this requires a separate class, since neither BO nor DTO should be related to converting them to another class.

I personally use the automapper library to convert objects. Using simple transformations, for example, in your example, the display is performed in a single line of code, complex transformations are also easily customizable.

If you want to map yourself, you can still use extension methods to keep the mapping implementation separate from your DTO and BO classes.

+11
source

I would suggest a component layer. He should be responsible for the communication between your business layer and your data layer. In this case, you can use it to translate DTO objects into Business Objects.

+1
source

You are worried that you do not need to expose the guts of business objects in the DTO, it seems a little unreasonable if your code does not have something that you do not show, because you are accessing public properties, that is, not the guts at all.

Alternatively, instead of cloning methods, you can implement the translation operator: MSDN

So you can do something like: Man p = (Man) myPersonDTO;

0
source

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


All Articles