在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