I have an ASP NET MVC 4 project with the following projects:
- Domain
- Repository
- Contracts (interfaces)
- DTO's
- And the web project
The web project "sees" only the repository project and it is responsible for executing the business rules. This project always returns DTO's to the web layer and in the web layer (controllers) I transform the DTO into a viewmodel and return the viewmodel to the view.
I'm using DTO's because in most queries I do not need all entity data, so I do not need to expose my entire entity to the view (and I also think it's not a good practice).
The problem I'm seeing is that it's redundant to return a DTO for my web layer and in the web layer transform the DTO into viewmodel. Here is an example:
Suppose that in the repository there is a method that returns user data (login and email) by id:
Method return DTO:
public class UsuarioDto{
public string Login {get; set;}
public string Email {get set;}
}
Method in repository that returns user to web layer
public class UsuarioRepositorio : IUsuarioRepository
{
public UsuarioDto GetUsuario(int usuarioId){
using(var context = new dbContext()) //instancia do contexto do entity
{
return context.Usuario.Select(x => new UsuarioDto{
Login = x.Login,
Email = x.Email
}
).FirstOrDefault(x.id == usuarioId);
}
}
}
At the point below I think I'm being redundant when transforming the DTO into a viewmodel
ViewModel that represents the user (within the Models folder)
public class UsuarioViewModel{
public string Login {get; set;}
public string Email {get set;}
}
Controller
public class HomeController : Controller
{
public ActionResult User(int usuarioId)
{
UsuarioRepositorio usuarioRepositorio = new UsuarioRepositorio();
var usuario = usuarioRepositorio.GetUsuario(usuarioId)
.Select(x => new UsuarioViewModel{
Login = x.Login,
Email = x.Email
}
);
return View(usuario)
}
}
Is there a way I can optimize this transformation from DTO to ViewModel? The impression I have is that I am duplicating code, because as far as I know, the DTO serves to traffic data between layers and the viewmodel is used to expose the data to the view.