
I have been learning C# and ASP.NET recently and came across this idea of Domain Model vs View Model.
I used to think that, as an example one single User model, is used from data layer to the presentation layer. However, in some cases, you might want to have different attributes for the User model in presentation layer and the data layer.
A common example would be, in a Sign up form (presentation layer), you might want to have these three attributes for User model: Username, Password and RePassword(Re-enter your password). In the database, we do not want to store RePassword attribute, and therefore we would use a different User model for database which only contains Username and Password.
You could define the method to retrieve User data in User services layer, and then map the retrieved User attributes that you want to the View User Model.
Let’s make another simple example.
We have an Employee model defined in Domain layer:
This Employee model is mapped to ApplicationDbContext, which is how our Employees information are stored in the database.
We need a method from Service Layer to retrieve this Employee context from ApplicationDbContext.
In our presentation layer, we define an Employee Controller to handle the mapping from Domain Employee model to View Employee model.
Appreciate if any of you would like to elaborate some use cases of independent View Model from Domain Model in the comment section below.
Cheers.
Originally published at https://dev.to on March 22, 2020.