Reputation: 1595
I want to check if i'm doing things right.
So I'm trying to create an API in .net core.
So this is the controller:
[HttpPost]
public IActionResult CreateAdministrator([FromBody]AdministratorViewModel administrator){
_unitOfWork.Administrators.Add(new Administrator
{
FirstName = administrator.FirstName,
LastName = administrator.LastName,
EmailAddress = administrator.EmailAddress,
Password = administrator.Password,
ManageAdministrators = administrator.ManageAdministrators
});
_unitOfWork.Complete();
}
So I have the AdministratorViewModel
as the object that contains the input the user does.
Then I pass the information to the Administrator
object to create a new administrator.
Is there a better way then just write all the time
property = administrator.property
. So if for example I add an extra field DateOfBirth
I have to add that on 3 different locations (viewmodel, model and controller.
Is there a way to just fill or 'merge' the properties of 2 objects so it autofills all filled in properties?
Or should I do this in a different way?
Upvotes: 2
Views: 138
Reputation: 1820
You could use automapper for that https://docs.automapper.org/en/stable/
Another approach you could create separate method like
Administrator ModelFromView (AdministratorViewModel viewModel)
{
//mapping code
}
But you have to add new mapped property to this method each time when you add new property to your class in this way. Automapper allows to avoid it. But sometimes you need more control for your mapping process and second approach might help you with it.
Upvotes: 3
Reputation: 109
Automapper is what you need
I used it in my production environment
Upvotes: 0
Reputation: 612
Not always the best approach to use AutoMapper. Interesting read here.
Upvotes: 0
Reputation: 286
You can create a copy constructor for your class AdministratorViewModel
and handle all the business logic there.
Afterwards you can just use:
_unitOfWork.Administrators.Add(new Administrator(administrator));
With this way you wouldn't have to add properties everywhere, when you later on decide to add more properties.
Upvotes: 2