Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper does not work for Lists?

Tags:

c#

automapper

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);
}
like image 881
Edwin Avatar asked Dec 09 '25 23:12

Edwin


1 Answers

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);
like image 53
Edwin Avatar answered Dec 11 '25 12:12

Edwin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!