ViewModels,CQRS和实体

我试图了解如何使用视图模型,命令和数据库实体

目前我认为这之间有很多手动映射,我不确定是否应该使用像AutoMapper这样的工具来映射ViewModel Command Entity当有很多属性时(比如10-15) )。

拿这个例子(在记事本中快速编写,可能无法编译 – 在我的实际应用中,我使用dependency injection和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 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); } } 

这里让我担心的是我在不同部分之间进行了大量的手动映射。 此示例仅包含一些属性。

我特别担心可能的更新命令很可能包含学生实体的所有可能属性。

有没有一个简洁的解决方案,或者我应该使用AutoMapper并从ViewModel CommandCommand Entity映射?

处理较少的类和映射/预测/转换的一种可能方法:

对于应用程序的WRITE-SIDE中使用的所有视图(允许用户提交表单的视图),请将Command作为其模型(View Model)。

也就是说,您可以:

 [HttpPost] public ActionResult Create(CreateStudent command) { commandHandler.Execute(command); } 

至于get动作 ,我看到你必须填充一个下拉列表……

 [HttpGet] public ActionResult Create() { // var model = create the view model somehow return View(model); } 

现在,对于后一个片段中的模型,您可能有这些选项(也许还有其他选项):

  • 让Command对象(CreateStudent)成为视图的模型(因为视图是…命令的视图,请求的视图)并使用ViewBag传递下拉项目
  • 派生自CreateStudent命令只是为了使它成为一个视图模型,它也可以保存下拉列表的项目

请注意,无需在命令对象中添加后缀“Command”。 只要给它一个名字,意思是doSomething – 一个动词短语(动词+对象) – 它应该没问题。

最后,一些命令对象确实是某些视图的模型 – 不需要为那些视图定义另一个视图模型,然后有很多重复等。

此外,您可能会发现这些有趣的: