Shaggy
Shaggy

Reputation: 5790

Automapper - map list of complex object to list of properties

I have following DomainObject class:

public class MyDomainObj
{
   public CUSTOMER customer {get;set;} // This is database entity
   public ORDER order {get;set;}
}

My DTO looks like this:

public class MyDTO
{
   public string custId{get;set;}
   public strinf orderId{get;set;}
}

Let's say in CUSTOMER table I have an attribute with the name: customer_id same for ORDER table its order_id

Here is my automapper configuration:

m.CreateMap<CUSTOMER, MyDTO>().ForMember(d => d.custId, o => o.MapFrom(s => s.customer_id));
m.CreateMap<ORDER, MyDTO>().ForMember(d => d.orderId, o => o.MapFrom(s => s.order_id));

I wrote an extension method for mapper in order to work:

public static class ExtensionAutoMapper
{
    public static TDestination Map<TSource, TDestination>(this TDestination destination, TSource source)
    {
        return Mapper.Map(source, destination);
    }
}

Usage is:

var response = Mapper.Map<MyDTO>(myDomainObj.customer)
                .Map(myDomainObj.order);

This works fine.

Question:

something along these lines

var response = Mapper.Map<List<MyDomainObj>, List<MyDTO>>(myDomainObj);

Edit: I would like to map fields in database entity to dto properties automatically if they have the same name.

Answer provided by @jmoerdyk, solve my problem. However, in that approach, I have to map all fields of a database entity to dto even if they have the same name.

Upvotes: 0

Views: 7215

Answers (1)

jmoerdyk
jmoerdyk

Reputation: 5521

You just provide the Mapping from MyDomainObj to MyDto, and it should be able to handle mapping the collections:

Mapper.CreateMap<MyDomainObj,MyDTO>()
    .ForMember(d => d.custId, o => o.MapFrom(s => s.customer.customer_id))
    .ForMember(d => d.orderId, o => o.MapFrom(s => s.order.order_id));

Then call it just like you had (assuming myDomainObj is a List<MyDominObj>):

var response = Mapper.Map<List<MyDomainObj>, List<MyDTO>>(myDomainObjList);

Upvotes: 2

Related Questions