2015-04-01 19 views
8

Ho cercato su StackOverflow e cercato su Google, ma non sono riuscito a trovare alcun aiuto o suggerimento su questo.Mappatura generica AutoMapper

Ho una classe come la seguente wich creare un oggetto PagedList e utilizza anche AutoMappper per mappare i tipi dalla sorgente alla destinazione

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

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

vorrei creare una mappa di questo tipo che dovrebbe convertirlo in un altro digitare come il seguente

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

ho provato con

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

ma il compilatore si lamenta a causa di TSrc e TDest

Qualche suggerimento?

risposta

13

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

Nel tuo caso questo sarebbe

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

Il compilatore si lamenta un errore 'PagedList' e dice' utilizzando il tipo di PagedList generica richiede due tipi arguments' – Lorenzo

+1

@Lorenzo: usare 'typeof (PagedList <,>) 'per indicare più tipi generici. –

+0

Grazie mille! – Lorenzo

0

Questa è una pratica migliore:

primo passo: creare una classe generice.

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

Secondo passo: ne fanno uso

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

     } 
Problemi correlati