C# – Should AutoMapper be used to Map from ViewModel back into Model

.net corecentity-framework

Should AutoMapper be used to take data from ViewModel and save back into a database model?

I know the opposite practice is good software practice: to have Automapper to extract database models, and place them in Viewmodels for front end web applications.

I was reading this general article here:
The article was not specifically about Automapper, but want to validate if the opinion is true.
https://stackoverflow.com/questions/35959968/best-way-to-project-viewmodel-back-into-model

"I believe best way to map from ViewModel to Entity is not to use AutoMapper for this. AutoMapper is a great tool to use for mapping objects without using any other classes other than static. Otherwise, code gets messier and messier with each added service, and at some point you won't be able to track what caused your field update, collection update, etc."

Best Answer

AutoMapper is simply a tool to facilitate mapping between objects; whether it should be used for mapping a ViewModel into an object used by the lower layers is not something that should be decided based on anything but whether it's useful in that specific mapping.

If you're handling an action where the ViewModel is very similar to the object you want to map to, such as this case:

    public class UserVM
    {
        public string Username { get; set; }
    }

    public class User
    {
        public string Username { get; set; }
    }

then yes, AutoMapper can be used without issues.

On the other hand, if the mapping requires logic, such as in this case:

    public class UserVM
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

    public class User
    {
        public string Username { get; set; }
        public string HashedPassword { get; set; }
        public string Salt { get; set; }

    }

I do not think you should use AutoMapper, but a separate service to handle the conversion.

As always, the answer is, I believe, it depends: you should first design your models without any concern or consideration towards AutoMapper or any other mapping tools, and then decide what's the best tool to accomplish what you need.