将扁平化存储过程值映射到导航 属性

Mapping flattened stored proc values to navigation property

这是我的存储过程 returns 一种 Customer_GetCustomers_Result:

SELECT c.*, a.City AS AddressCity, a.State AS AddressState
FROM Customer c
LEFT OUTER JOIN Address a ON c.AddressId = a.Id

当使用 AutoMapper 从 Customer_GetCustomers_Result 映射到 Model.Customer (POCO) 时,我希望 AddressCity 和 AddressState 映射到 Customer.Address.City 和 Customer.Address.State。

我认为使用此命名约定我不必向我的 AutoMapper 配置添加任何特殊内容,除了:

CreateMap<Customer_GetCustomers_Result, Model.Customer>();

我愿意做任何事情来从我的存储过程中获取要映射的导航属性。有什么想法吗?

您可以使用 AfterMap:

Mapper.CreateMap<Customer_GetCustomers_Result, Model.Customer>()
    .AfterMap((s,t) => 
    {
        t.Address = new Address { 
                                    City = s.AddressCity, 
                                    State = s.AddressState
                                };
    });

或者甚至定义第二个映射...

Mapper.CreateMap<Customer_GetCustomers_Result, Address>()
    .ForMember(t => t.City, m => m.MapFrom(s => s.AdressCity))
    .ForMember(t => t.State, m => m.MapFrom(s => s.AdressState))

然后...

Mapper.CreateMap<Customer_GetCustomers_Result, Model.Customer>()
    .AfterMap((s,t) => 
    {
        t.Address = Mapper.Map<Address>(s);
    });