AutoMapper generic mapping

Lorenzo picture Lorenzo · Apr 1, 2015 · Viewed 20.9k times · Source

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?

Answer

Jeroen Vannevel picture Jeroen Vannevel · Apr 1, 2015

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