Another question I asked on here has opened a can of worms for me. Currently I have development my MVC application, with models representing my data and used scaffolding to generate my ViewControllers from those models. Where the models didn't have the required information in, I was using partial views to show the relevant information. After some reading I now understand ViewModel's to be the better way of doing things. So my understand is that for each view I will have a specific ViewModel that returns the data for that view.
I have two models, one representing an item and the other, the item options of which there may be multiple.
public class Item
{
public int ItemId { get; set; }
public bool Active { get; set; }
public string ItemCode { get; set; }
public string Name { get; set; }
public List<ItemOption> ItemOptions { get; set; }
//...
}
public class ItemOption
{
public int ItemOptionId { get; set; }
public string Name { get; set; }
public string Barcode { get; set; }
//...
}
Therefore I assume my ItemDetailViewModel will just contain the information I show to the user in the view:
public class ItemDetailViewModel
{
public bool Active { get; set; }
public string ItemCode { get; set; }
public string Name { get; set; }
public List<ItemOption> ItemOptions { get; set; }
}
Should I be making my ItemOptions list on the ItemDetailViewModel there own list? For example should it be:
public List<ItemOptionsViewModel> ItemOptions { get; set; }
I think I am missing the benefit of the ViewModel. I've read that it's so we can have all the data in one class relevant for that view and therefore we can keep the view strongly typed. However I seem to just be copying my Models into my ViewModels, so not really gaining any benefit.
In addition, my research has lead me to thinkking AutoMapper is the best way forward. Am I correct in saying I just put the following in my start up config:
Mapper.CreateMap<Item, ItemDetailViewModel>()
.ForMember(x => x.Active, o => o.MapFrom(s => s.Active))
.ForMember(x => x.ItemCode, o => o.MapFrom(s => s.ItemCode))
.ForMember(x => x.Name, o => o.MapFrom(s => s.Name));
.ForMember(x => x.ItemOptions, o => o.MapFrom(s => s.ItemOptions));
If I do this, how does it work for the edit views. If I save them back to the ItemDetailViewModel will it update my database in EF?
Mapper.CreateMap<Item, ItemDetailViewModel>();
will suffice). – NallHasItemOptions
might be useful for data binding. Or the property setter forName
might store invalid names (to be fixed before saving) where the model property setter would immediately throw an exception. – Refugia