6
I am assembling an application following the DDD standards. I would like to know how to properly use the Data Transfer Object - DTO standard.
With the little I’ve read, I’ve come to the conclusion: I am using Viewmodel (an entity representation to be used in the View), so I need to convert this Viewmodel to DTO to transmit to the other layers. Coming to the domain, I need to convert again from DTO to entity and send the entity to the repository (persistence). The reverse path is also necessary in the case of consultation.
The question is: Can I have a constructor in Viewmodel that receives a DTO and create a Viewmodel from it? And in DTO a constructor that creates a DTO from a Viewmodel? The same for the entity.
For example:
public Class UsuarioViewModel{
public string Nome {get; set;}
public string EMail {get; set;}
public string Senha {get; set;}
public UsuarioViewModel(){
}
public UsuarioViewModel(UsuarioDTO _usuariodto){
Nome = _usuariodto.Nome,
EMail = _usuariodto.EMail,
Senha = _usuariodto.Senha
}
}
public Clas UsuarioDTO{
public string Nome {get; set;}
public string EMail {get; set;}
public string Senha {get; set;}
public UsuarioDTO(){
}
public UsuarioDTO(UsuarioViewModel _usuariovm){
Nome = _usuariovm.Nome,
EMail = _usuariovm.EMail,
Senha = _usuariovm.Senha
}
public UsuarioDTO(Usuario _usuario){
Nome = _usuario.Nome,
EMail = _usuario.EMail,
Senha = _usuario.Senha
}
}
public Clas Usuario{
public string Nome {get; set;}
public string EMail {get; set;}
public string Senha {get; set;}
public Usuario(){
}
public UsuarioDTO(UsuarioDTO _usuarioDTO){
Nome = _usuarioDTO.Nome,
EMail = _usuarioDTO.EMail,
Senha = _usuarioDTO.Senha
}
}
// Controller
_serviceApp.Add(new UsuarioDTO(usuarioVM));
//Service
_service.Add(new Usuario(usuarioDTO));
//Repositorio
_repositorio.add(Usuario usuario);
I can work that way?
Of a deal here, It may help. I think(Opinion), that in most cases, MVVM already solves 90% of cases. As Renan said in his reply "I see no need of DTO unless you make many remote calls to recover lots of data"
– Barbetta
@Diego Rafael Souza Thank you for the Reply! Legal, use DTO in more complex situations... Now, in relation to MVVM it would be something like: public void Add(Clientevm) { var client = new Client() { Client = vm.Client, Name = vm.Name, CPF = vm.CPF, }; _client Add(client); } Simply convert from Viewmodel to Entity and Vice and Versa? If not so, could you give me an example?
– Rafael Arthur
@Barbetta Thank you too!
– Rafael Arthur
@Diegorafaelsouza if I understand correctly, you are doubtful about passing the data from
ViewModel
to theModel
, correct, maybe this one reply and that another answer help you.– Barbetta