Edwin
Edwin

Reputation: 961

Automapper does not work for Lists?

I have two classes, Sale and SaleDTO.

When I map objects of these two classes using automapper, it will work.

However, if I do something like this:

List<Sale> s = GetSalesFromDatabaseMethod();
List<SaleDTO> sa = Mapping.Map<List<Sale>, List<SaleDTO>>(s);

sa will turn up empty. Am I doing something wrong?

The Map method is basically a shortcut to mapping:

public static H Map<T, H>(T i) {
    Mapper.CreateMap<T, H>();
    return Mapper.Map<T, H>(i);
}

Upvotes: 2

Views: 8616

Answers (2)

Guilherme Golfetto
Guilherme Golfetto

Reputation: 530

I don't know if somebody has the same error as I do.

Here's my way to resolve this:

List<Sale> s = GetSalesFromDatabaseMethod();
List<SaleDTO> sa = s.Select(item => (Sale) item).ToList();

Upvotes: -1

Edwin
Edwin

Reputation: 961

I found the answer from Automapper copy List to List.

Apparently the shortcut Mapping.Map<>() that I made method would not work, as I need to create the map to the two classes first and then map the lists, like so:

Mapper.CreateMap<Sale, SaleDTO>();
List<SaleDTO> sa = Mapper.Map<List<Sale>, List<SaleDTO>>(s);

Upvotes: 11

Related Questions