2015-04-01 260 views
8

我在StackOverflow上搜索並搜索了它,但我還沒有找到任何幫助或建議。AutoMapper通用映射

我有這樣一類以下至極創建PagedList對象並且還使用AutoMappper從源類型映射到目的地

public class PagedList<TSrc, TDest> 
{ 
    protected readonly List<TDest> _items = new List<TDest>(); 

    public IEnumerable<TDest> Items { 
     get { return this._items; } 
    } 
} 

我想創建這種類型的地圖應該把它轉換成另一種鍵入像

public class PagedListViewModel<TDest> 
{ 
    public IEnumerable<TDest> Items { get; set; } 
} 

我與

Mapper.CreateMap<PagedList<TSrc, TDest>, PagedListViewModel<TDest>>(); 
嘗試以下

但編譯器抱怨,因爲TSrcTDest

任何建議嗎?

回答

13

根據the AutoMapper wiki

public class Source<T> { 
    public T Value { get; set; } 
} 

public class Destination<T> { 
    public T Value { get; set; } 
} 

// Create the mapping 
Mapper.CreateMap(typeof(Source<>), typeof(Destination<>)); 

在你的情況,這將是

Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>)); 
+0

編譯器會抱怨'PagedList'錯誤,並說'使用通用型PagedList需要兩種類型arguments' – Lorenzo 2015-04-01 00:52:17

+1

@Lorenzo:使用'typeof運算(PagedList <,>)'來表示多個泛型類型。 – 2015-04-01 00:53:35

+0

非常感謝! – Lorenzo 2015-04-01 00:55:47

0

這是最佳的做法:

第一步:創建一個generice類。

public class AutoMapperGenericsHelper<TSource, TDestination> 
    { 
     public static TDestination ConvertToDBEntity(TSource model) 
     { 
      Mapper.CreateMap<TSource, TDestination>(); 
      return Mapper.Map<TSource, TDestination>(model); 
     } 
    } 

第二步: 不要使用它

[HttpPost] 
     public HttpResponseMessage Insert(LookupViewModel model) 
     { 
      try 
      { 
       EducationLookup result = AutoMapperGenericsHelper<LookupViewModel, EducationLookup>.ConvertToDBEntity(model); 
       this.Uow.EducationLookups.Add(result); 
       Uow.Commit(User.Id); 
       return Request.CreateResponse(HttpStatusCode.OK, result); 
      } 
      catch (DbEntityValidationException e) 
      { 
       return Request.CreateResponse(HttpStatusCode.InternalServerError, CustomExceptionHandler.HandleDbEntityValidationException(e)); 
      } 
      catch (Exception ex) 
      { 
       return Request.CreateResponse(HttpStatusCode.BadRequest, ex.HResult.HandleCustomeErrorMessage(ex.Message)); 
      } 

     }