I am trying to understand how to probably make use of a view model, a command and the database entity
At the moment I think there is a lot of manual mapping between this, and I am unsure if I should use a tool like AutoMapper to map ViewModel <-> Command <-> Entity
when there is a lot of properties (like 10-15).
Take this example (written quickly in notepad, may not compile - in my real applicaiton I use dependency injection and IoC):
public class Student {
public int Id { get; set; }
public string Name { get; set; }
public string AnoterProperty { get; set; }
public string AnoterProperty2 { get; set; }
public string AnoterProperty3 { get; set; }
public string AnoterProperty4 { get; set; }
public string AnoterProperty5 { get; set; }
public int StudentTypeId { get; set; }
public StudentType StudentType { get; set; } // one-to-many
}
public class CreateStudentViewModel {
public string Name { get; set; }
public DropDownList StudentTypes { get; set; }
}
public class DropDownList {
public string SelectedValue { get; set; }
public IList<SelectListItem> Items { get; set; }
}
public class CreateStudent {
public string Name { get; set; }
public int StudentTypeId { get; set; }
}
public class HandleCreateStudentCommand {
public void Execute(CreateStudent command) {
var student = new Student {
Name = command.Name,
StudentTypeId = command.StudentTypeId
};
// add to database
}
}
public class StudentController {
public ActionResult Create() {
var model = new CreateStudentViewModel {
StudentTypes = new DropDownList {
Items = // fetch student types from database
}
};
return View(model);
}
public ActionResult Create(CreateStudentViewModel model) {
var command = new CreateStudent {
Name = model.Name,
StudentTypeId = Convert.ToInt32(model.Items.SelectedValue);
};
var commandHandler = new HandleCreateStudentCommand();
commandHandler.Execute(command);
}
}
What worries me here is that I do a lot of manual mapping between the different parts. And this example only contains a few properties.
I am especially worried about a possible update command which will most likely contain all possible properties of the student entity.
Is there a neat solution, or should I go with AutoMapper and map from ViewModel <-> Command
and Command <-> Entity
?