我在这里http://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/如何你可能不应该试图读取非扁平化扁平物体,但考虑到我是如何使用存储库实体框架,实体模型是预期的,而不是ViewModels。域模型视图模型,然后再返回使用存储库模式和Entity Framework在MVC3
我开始想我是否应该采取不同的方法,没有任何人有这样的事情的最佳做法?还是刚开始使用ValueInjector Using AutoMapper to unflatten a DTO?而不是太在意将RecipeCreateViewModel映射回配方?
下面是我的代码给你什么,我目前所面对的一个想法。
// Entities
public class Recipe {
public int Id { get; set; }
public string Name { get; set; }
public Course Course { get; set; }
}
public class Course {
public int Id { get; set; }
public string Name { get; set; }
}
// View Model
public class RecipeCreateViewModel {
// Recipe properties
public int Id { get; set; }
public string Name { get; set; }
// Course properties, as primitives via AutoMapper
[Required]
public int CourseId { get; set; }
// Don't need CourseName in the viewmodel but it should probably be set in Recipe.Course.Name
//public string CourseName { get; set; }
// For a drop down list of courses
public SelectList CourseList { get; set; }
}
// Part of my View
@model EatRateShare.WebUI.ViewModels.RecipeCreateViewModel
...
<div class="editor-label">
Course
</div>
<div class="editor-field">
@* The first param for DropDownListFor will make sure the relevant property is selected *@
@Html.DropDownListFor(model => model.CourseId, Model.CourseList, "Choose...")
@Html.ValidationMessageFor(model => model.CourseId)
</div>
...
// Controller actions
public ActionResult Create() {
// map the Recipe to its View Model
var recipeCreateViewModel = Mapper.Map<Recipe, RecipeCreateViewModel>(new Recipe());
recipeCreateViewModel.CourseList = new SelectList(courseRepository.All, "Id", "Name");
return View(recipeCreateViewModel);
}
[HttpPost]
public ActionResult Create(RecipeCreateViewModel recipe) {
if (ModelState.IsValid) {
// set the course name based on the id that was posted
// not currently checking if the repository doesn't find anything.
recipe.CourseName = courseRepository.Find(recipe.CourseId).Name;
var recipeEntity = Mapper.Map<RecipeCreateViewModel, Recipe>(recipe);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();
return RedirectToAction("Index");
} else {
recipe.CourseList = new SelectList(courseRepository.All, "Id", "Name");
return View(recipe);
}
}
感谢Mike的回答,我的问题不是很清楚,因为我不确定几件事情,并且一次询问几件事情。即时消息关闭后,您已经清楚地了解了创建和显示图层。我一直在努力的问题是从视图模型返回映射。 – Pricey 2012-03-29 15:53:45
@MikeSW为什么在从PM转换回VM时跳过域模型?从DM映射你的VM不是更好吗?这样你在上层只做一次。 – 2013-04-19 14:59:00
@JoaoLeme不是。显示更新视图模型只需要从持久性实体已经可用的模型中保存数据。所以不是填充整个对象,而是直接查询存储以获取相关数据。这几乎是CQRS – MikeSW 2013-04-19 15:15:10