3
votes

I have two classes:

public class CustomerDTO
{

public string Name {get;set;}
public List<Order> Orders {get;set;}

}

public class OrderDTO
{
public string Name {get;set;}
public string Description {get;set;}
public decimal Cost{get;set;}
}

I am using AutoMapper for .NET 3.5 and currently doing the following in my Application_StartUp:

Mapper.CreateMap<Customer, CustomerDTO>();
Mapper.CreateMap<Order,OrderDTO>();

This is a simplified example as I named my DTO properties different than my entity properties, so I used ForMember, but I am unclear on how to map Orders to Customer:

I tried:

Mapper.CreateMap<Customer, CustomerDTO()
.ForMember(dest => dest.Orders, opt=> opt.MapFrom(src=>src.Orders));

but it does not find src.Orders.

If I do indeed need to have both CreateMap statements, does AutoMapper "automatically" link the objects Customer to Orders?

1
In the code you posted, CustomerDTO has an orders not an Orders property. Is that just a typo in the posting? If it is as posted than that would be an issue, property names are case sensitive.pstrjds
Also, if your map is 1 to 1, then you can just do Mapper.Map(cust, custDTO)Justin Pihony
shouldn't the code also be ListMOrdersDTO> Orders {get;set};??MethodMan
Can you post your Ordem and Custumer classes? Maybe the type of Orders properties isn't the same.fhelwanger
@JustinPihony - This is the confusing part to me. I understand the mapping cust to CustDTO, but how do I map OrdersDTO to the CustDTO?Xaisoft

1 Answers

0
votes

Yes, you need to tell AutoMapper about each mapping. It will not guess for you. So, if an OrderDTO should map to an Order, you must tell AutoMapper that. You must also specify the reverse relationship if that's needed as well (i.e. Order should map to OrderDTO).

In other words, for bi-directional mapping you would need:

Mapper.CreateMap<Order, OrderDTO>();
Mapper.CreateMap<OrderDTO, Order>();

As far as Customer goes, if both Customer and CustomerDTO have a property named Orders, you don't need to do anything else. As long as you've told AutoMapper to map between Order and OrderDTO and Customer and CustomerDTO, it will automatically map your Order when you map Customer.