I'm curious as to what people consider better practice, between duplicating model structure in the view model and using a mapping tool to move data between the two, or aggregate the model inside the view model, i.e. have a property on the view mod开发者_StackOverflow社区el class that is a reference to the actual model. Which is considered a better approach in general?
The "better" approach will always be having a distinct view model for each view, and then using AutoMapper or something similar to handle the guts of the mappings for you
public class MyViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public MyViewModel() { }
public MyViewModel( MyModel model )
{
AutoMapper.Mapper.Map(model, this);
}
}
It will vary in practice sometimes, but having a distinct, concise viewmodel will offer the most flexibility.
精彩评论