在this article,Jimmy Bogard继续解释他在做MVC时所赞同的一些最佳实践。通过动作过滤器属性将实体自动映射到模型?
这篇文章总的来说非常好,我发现他的建议(在其他博客文章中)非常稳固。但是,他建议使用属性将实体映射到模型。
这是怎么
[AutoMap(typeof(Product), typeof(ShowProduct))]
public ActionResult Details(int id)
{
var product = _productRepository.GetById(id);
return View(product);
}
任何比这更好(这在我看来是对一段代码
public ActionResult Details(int id)
{
var product = _productRepository.GetById(id);
var model = Mapper.Map<Product, ShowProduct>(product);
return View(model);
}
的实际意图的方式更具声明除了有一点,有似乎是这样的情况,这是不切实际的,例如根据输入返回不同模型的动作方法,或者甚至更简单的情况,例如:
[HttpGet]
public ActionResult Index()
{
return List();
}
public ActionResult Until(long id) // "id" is the timestamp
{
return List(id);
}
[NonAction]
internal ActionResult List(long? timestamp = null, int count = 8)
{
IEnumerable<Post> posts = postService.GetLatest(timestamp, count);
PostListModel model = mapper.Map<IEnumerable<Post>, PostListModel>(posts);
return ContextView("List", model);
}
这实际上是一种很好的做法,或者只是没有道理,对代码的无理混淆已经很简单了吗?
我问出于无知,不是亲自攻击我认为是一个很棒的博客的人,除了我已经喜欢AutoMapper。
他甚至进一步采取它在这个视频:http://www.viddler.com/v/b568679c。他创建了一个ActionResult,它为您执行AutoMapping。他的控制器行动令人难以置信的小。向前跳到ActionResults点,看看他做了什么。 – 2012-08-07 01:28:29
+1伟大的问题和资源。 Mapper.Map AutoMapper的功能,还是它的包装? – 2013-02-04 16:42:47
它是'AutoMapper'的引擎包装(它仍然是单元测试的) – bevacqua 2013-02-04 16:47:11