Automapper not behaving properly
I have this line of code in my global.asax
Mapper.CreateMap<Order, OrderDTO>();
These are my classes:
public class Customer
{
public string Name {get; set;}
}
public class Order
{
public int OrderId { get; set; }
public Customer Customer { get; set; }
}
public class OrderDTO
{
public int OrderId { get; set; }
public string Name { get; set; }
}
And this is my code:
Customer cust = new Customer { Name = "Jaggu" };
Order order = new Order { Customer = cust, OrderId = 123 };
OrderDTO dto = Mapper.Map<Order,OrderDTO>(order);
my dto contains OrderId but Name is null. As per documentation it should work:
https://github.com/AutoMapper/AutoMapper/wiki/Flattening
If I change my global.asax's mapping to this:
Mapper.CreateMap<Order, OrderDTO>().ForMember(dest => dest.Name,
mapping => mapping.MapFrom(order => order.开发者_JAVA技巧Customer.Name));
it works! This make me curious. Is the doc wrong? or am I doing it wrong?
It will work if you follow the standard naming convention:
public class OrderDTO
{
public int OrderId { get; set; }
public string CustomerName { get; set; }
}
Notice that the property is called CustomerName
and not Name
. When flattening the Order
model into a Dto
, the Customer.Name
goes into CustomerName
.
精彩评论