2015-04-01 15 views
8

Tôi đã tìm kiếm trên StackOverflow và googled về nó nhưng tôi havent đã có thể tìm thấy bất kỳ trợ giúp hoặc gợi ý về điều này.AutoMapper generic mapping

Tôi có một lớp như sau Mà tạo ra một đối tượng PagedList và cũng sử dụng AutoMappper để lập bản đồ các loại từ nguồn tới đích

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

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

Tôi muốn tạo ra một bản đồ cho loại hình này nên chuyển nó sang khác gõ như sau

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

tôi đã thử với

Mapper.CreateMap<PagedList<TSrc, TDest>, PagedListViewModel<TDest>>(); 

nhưng trình biên dịch than phiền vì TSrcTDest

Bất kỳ đề xuất nào?

Trả lời

13

Theo 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<>)); 

Trong trường hợp của bạn này sẽ là

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

Trình biên dịch phàn nàn về lỗi trên 'PagedList' và nói' bằng cách sử dụng loại PagedList chung đòi hỏi hai loại arguments' – Lorenzo

+1

@Lorenzo: sử dụng 'typeof (PagedList <,>) 'để chỉ ra nhiều loại chung chung. –

+0

Cảm ơn bạn rất nhiều! – Lorenzo

0

Đây là một thực hành tốt nhất:

bước đầu tiên: tạo ra một lớp generice.

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

bước thứ hai: Đừng Sử dụng nó

[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)); 
      } 

     }