2015-04-01 15 views
8

Szukałem na StackOverflow i googled o tym, ale nie byłem w stanie znaleźć żadnej pomocy lub sugestii na ten temat.Generyczne mapowanie AutoMappera

Mam klasy jak poniżej wich tworzyć PagedList obiekt, a także wykorzystuje AutoMappper do mapowania typów od źródła do miejsca przeznaczenia

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

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

Chciałbym stworzyć mapę dla tego rodzaju, że należy przekonwertować go na inny wpisz jak poniżej

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

próbowałem z

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

ale kompilator narzeka z powodu: TSrc i TDest

Jakieś sugestie?

Odpowiedz

13

Według 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<>)); 

W twoim przypadku będzie to

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

Kompilator narzeka błędu 'PagedList' i mówi' stosując ogólny typ PagedList wymaga dwa rodzaje arguments' – Lorenzo

+1

@Lorenzo: użyj 'typeof (PagedList <,>) 'do wskazania wielu rodzajów ogólnych. –

+0

Dziękuję bardzo! – Lorenzo

0

Jest to najlepsza praktyka:

pierwszy krok: utworzyć klasę generice.

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

Drugi etap: używaj go

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

     }