2011-01-06 30 views
0

我有我的viewmodel類和我的wcf服務類(單獨的項目)。我需要將視圖模型類轉換爲wcf類,也是相反的方式。目前我使用以下方法:使用AutoMapper的雙向轉換

public static class ExtensionMethods 
{ 
    public static object To<T>(this object source) 
    { 
     // create the map 
     Mapper.CreateMap(source.GetType(), typeof (T)); 

     // if the source is a list 
     if(source is IEnumerable) 
     { 
      return Mapper.Map(source, source.GetType(), typeof (List<T>)); 
     } 

     // return the mapping 
     return (T) Mapper.Map(source, source.GetType(), typeof (T)); 
    } 

} 

// converting the wcf class to viewmodel 
var orders = (List<OrderStatusViewModel>) _orderStatusServiceClient.GetRecentOrders().To<OrderStatusViewModel>(); 
// converting the viewmodel to the wcf class 
var order = (Order) orderStatusViewModel.To<Order>(); 

這是最好的方法嗎?請記住,我必須在兩個方向執行此操作,即viewmodel => wcf類和wcf類=> viewmodel。

+0

「最好做這道」的問題可能會非常棘手有效回答。一眼看,我沒有看到問題。 **此代碼是否會導致問題?你的問題是什麼原因? – 2011-01-06 20:45:16

回答

0

要注意的一件事是重新定義你的地圖一次又一次。我的代碼已經被炸掉了。

由於您的方法沒有綁定到任何特定的類型,我建議刪除CreateMap調用並將Map調用更改爲DynamicMap。

另外,如果您的泛型參數類型爲IEnumerable的,當你輸入的是,那麼你如果是不必要的與DynamicMap