Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper generic mapping

Tags:

I have searched on Stack Overflow and googled about it but I haven't been able to find any help or suggestion on this.

I have a class like the following which create a PagedList object and also uses AutoMappper to map types from source to destination.

public class PagedList<TSrc, TDest> {     protected readonly List<TDest> _items = new List<TDest>();      public IEnumerable<TDest> Items {         get { return this._items; }     } } 

I would like to create a Map for this type that should convert it to another type like the following

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

I have tried with

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

but the compiler complains because of TSrc and TDest

Any suggestion?

like image 288
Lorenzo Avatar asked Apr 01 '15 00:04

Lorenzo


People also ask

Is AutoMapper faster than manual mapping?

Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full . NET Framework).

What can I use instead of AutoMapper?

AutoMapper is one of the popular object-object mapping libraries with over 296 million NuGet package downloads. It was first published in 2011 and its usage is growing ever since. Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.

Can AutoMapper map collections?

AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.


1 Answers

According to 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<>)); 

In your case this would be

Mapper.CreateMap(typeof(PagedList<,>), typeof(PagedListViewModel<>)); 
like image 55
Jeroen Vannevel Avatar answered Sep 21 '22 23:09

Jeroen Vannevel