Sam
Sam

Reputation: 15761

AutoMapper Questions

I have a couple questions about AutoMapper.

1) I have a class named Category and a View Model named CategoryViewModel. Do I need to create mappings for each direction?

Mapper.CreateMap(Of Category, CategoryViewModel)
Mapper.CreateMap(Of CategoryViewModel, Category)

2) How do I map collections? I have a CategoryListViewModel that has a single property of IEnumberable(Of CategoryViewModel). I wan to populate those from my service that return IQueryable(Of Category)?

Thanks!!

Upvotes: 1

Views: 746

Answers (1)

Shan Plourde
Shan Plourde

Reputation: 8706

  1. You only have to define the mapping one time. AutoMapper is smart enough to figure out how to map from both directions

  2. AutoMapper is smart enough to know how to map to collections once you've registered your type mappings by calling .CreateMap(). So you don't have to create a type mapping for collections of your mapped types. AutoMapper will traverse your collections and map each object contained within.

To have AutoMapper map to a list, simply call List<TypeTo> destination = Mapper.Map<List<TypeFrom>, List<TypeTo>)(sourcObject);

In VB that may look like the following source, which I ran through a C# to VB.NET converter:

Mapper.Map<List<TypeFrom>, List<TypeTo>)(sourcObject);

Upvotes: 4

Related Questions