Populating ViewModel from EntityModel and Vice Versa in a controller

asp.net-mvc-5 entity-framework-6

Question

I have started working with MVC for sometime now and I am learning different approached to different scenarios. There can be different ways of handling a single scenario and it can be quite debatable that which one is more effective and better then other.

My confusion is related to the use of Entity models and View Models. I have created separate entity models for every database entity and also create separate view models for every view. Now I have a simple view with textboxes, radio buttons, checkboxes and dropdown lists on it. I have two way databinding on the view and I use the same view for creating new records and editing existing records.

My confusion is that I am retrieving the entity model from the database and populating each field of ViewModel from the entity model and then passing the ViewMoel to the model. Now this has to be done manually for each field. So is there some way through which the ViewModel adn Entity Models are auto mapped on the runtime? For example, on one simple view I am doing the following,

List<User> UserList = db.Users.ToList();

        List<UserViewModel> UsersViewModel = new List<UserViewModel>();
        foreach (User user in UserList)
        {
            UserViewModel model = new UserViewModel();
            model.FirstName = user.FirstName;
            model.LastName = user.LastName;
            model.DOB = user.DOB;
            model.Addresses = user.Addresses;
        }

When the ViewModel is populated manually I pass it to the view. Also for saving the records to the database I do the opposite and populates the Entity model from ViewModel. To me there must be some more effective and shorter way of doing what I am doing. I have checked a similar question here at MVC4 C# Populating data in a viewmodel from database but it is not answering my question and rather addressing some error.

1
1
5/23/2017 12:25:40 PM

Accepted Answer

Use a tool like AutoMapper. Once you configure the mappings you can populate your view models like so:

var user = db.Users.First();
var uservm = Mapper.Map<UserViewModel>(user);

var users = db.Users.ToList();
var usersvm = Mapper.Map<IEnumerable<UserViewModel>>(users);

Generally, the auto mapping is one-way and safe only for Entity to View Model. Mapping back to the Entity type is still manually done.

As for your manual example, for performance reasons, you want to use a projection instead of iterating:

var users = db.Users.Select(u => new UserViewModel {
    FirstName = u.FirstName,
    LastName = u.LastName,
    ...
});
2
7/8/2015 7:00:46 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow