2012-08-07 50 views
2

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。

+0

他甚至進一步採取它在這個視頻:http://www.viddler.com/v/b568679c。他創建了一個ActionResult,它爲您執行AutoMapping。他的控制器行動令人難以置信的小。向前跳到ActionResults點,看看他做了什麼。 – 2012-08-07 01:28:29

+0

+1偉大的問題和資源。 Mapper.Map AutoMapper的功能,還是它的包裝? – 2013-02-04 16:42:47

+0

它是'AutoMapper'的引擎包裝(它仍然是單元測試的) – bevacqua 2013-02-04 16:47:11

回答

1

我的想法是將映射放在控制器上更好,因爲它可以讓你隱藏實際映射實現的一些細節。您還可以獲得更高的靈活性,以便稍後更改一個文件中的映射,而不是在7個以上的操作方法中更改此調用。這假設了純粹的基本CRUD行動。在這種情況下可能會出現特殊的用例,在這些情況下做出不同的事情對我來說是很好的。

這只是我的2美分。

2

我在做這個話題的搜索,也碰到了洛杉磯郵報。我在AutoMapper-users組中搜索了這個Google Groups article

它看起來像吉米已從該指導退堂鼓:

不要使用行爲過濾器。我們最初自己走了這條路線,但最終還是以自定義行動結果爲基礎。這是一個小小的 更容易定製那些超過行動過濾器,這使得它非常不可能提供自定義行爲。

HTH,

吉米

+0

下面是這種ViewResult的實現:https://github.com/jbogard/presentations/blob/master/FullSystemTesting/Code/UI/Helpers/ AutoMapViewResult.cs – Giorgi 2014-09-25 12:41:46

相關問題