Reputation: 185
When using Entity Framework code-first for example, is it advisable to use DTO classes inside your view model? Or should you directly use the entity classes?
I currently do it this way to not have to use [NotMapped]
attribute and set some calculated properties on my DTO instead.
I guess it also has the benefit of not having to apply validation annotations directly on the entity class.
The reason for this question is if this is the correct way to go. What are your thoughts?
Upvotes: 0
Views: 330
Reputation: 258
You're on the right path. Definitely don't use EF models in your ViewModel. It creates a coupling between the database and the UI.
However... Using the dtos in viewmodel are but can cause problems when your UI diverges from the underlying api.
Unless it's a very small application I would tend to have models that I compose to make ViewModels and use something like AutoMapper to transfer the data between the UI model and the DTO.
You can use the same technique on the back end to transfer data bewteen the DTO and the EF model.
This keeps the DTO simple as it only has one job - transferring data at the api level. It neither knows nor cares about the UI or the database.
Upvotes: 1