自动映像表现不正常

时间:2011-09-09 06:10:32

标签: c# automapper

我的global.asax

中有这行代码
Mapper.CreateMap<Order, OrderDTO>();

这些是我的课程:

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; }

    }

这是我的代码:

Customer cust = new Customer { Name = "Jaggu" };

Order order = new Order { Customer = cust, OrderId = 123 };

OrderDTO dto = Mapper.Map<Order,OrderDTO>(order);

我的dto包含OrderId,但Name为null。根据文档,它应该工作:

https://github.com/AutoMapper/AutoMapper/wiki/Flattening

如果我将global.asax的映射更改为:

Mapper.CreateMap<Order, OrderDTO>().ForMember(dest => dest.Name, 
       mapping => mapping.MapFrom(order => order.Customer.Name));

它有效!这让我很好奇。这个文件错了吗?或者我做错了吗?

1 个答案:

答案 0 :(得分:5)

如果您遵循标准命名约定,它将起作用:

public class OrderDTO
{
    public int OrderId { get; set; }
    public string CustomerName { get; set; }
}

请注意,该属性名为CustomerName,而不是Name。将Order模型展平为Dto时,Customer.Name会进入CustomerName