使用自动映射器映射嵌套对象 [英] Using automapper to map nested objects

查看:95
本文介绍了使用自动映射器映射嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Customer EF POCO类,其中包含对Address表的引用.

I have a Customers EF POCO class which contains a reference to the Address table.

以下代码似乎有效,但是我不确定这是最干净的方法.有没有更好的方法可以仅使用一个Map调用来映射它?

The following code seems to work, but I'm not sure it's the cleanest way to do this. Is there a better way to map this using only a single Map call?

    [HttpGet]
    public ActionResult Details(string ID)
    {
        BusinessLogic.Customers blCustomers = new BusinessLogic.Customers("CSU");
        DataModels.Customer customer = blCustomers.GetCustomer(ID);

        CustomerDetailsViewModel model = new CustomerDetailsViewModel();

        Mapper.CreateMap<DataModels.Customer, CustomerDetailsViewModel>();
        Mapper.CreateMap<DataModels.Address, CustomerDetailsViewModel>();
        Mapper.Map(customer, model);
        Mapper.Map(customer.Address, model);

        return View(model);
    }

推荐答案

这取决于您的CustomerDetailsViewModel外观.例如,如果您的Address类看起来像这样:

It depends on what your CustomerDetailsViewModel looks like. For example, if your Address class looks something like this:

public class Address 
{
    public string Street { get; set; }
    public string City { get; set; }
}

CustomerDetailsViewModel包含遵循以下约定的属性:

and CustomerDetailsViewModel contains properties following this convention:

在AutoMapper中配置源/目标类型对时, 配置器尝试匹配源上的属性和方法 输入目标类型上的属性.如果是关于 目标类型键入属性,方法或以"Get"为前缀的方法 源类型上不存在,AutoMapper拆分目标 成员名称转换成单个单词(按照PascalCase约定).

When you configure a source/destination type pair in AutoMapper, the configurator attempts to match properties and methods on the source type to properties on the destination type. If for any property on the destination type a property, method, or a method prefixed with "Get" does not exist on the source type, AutoMapper splits the destination member name into individual words (by PascalCase conventions).

(来源:平化)

然后,如果CustomerDetailsViewModel具有属性:

public string AddressStreet { get; set; }
public string AddressCity { get; set; }

只需一个从CustomerCustomerDetailsViewModel的映射即可.对于不符合该约定的成员,可以使用ForMember.

Just one mapping from Customer to CustomerDetailsViewModel will work. For members that don't match that convention, you could use ForMember.

对于每个单个地址属性,您也始终可以使用ForMember:

You can always use ForMember for every single address property as well:

Mapper.CreateMap<DataModels.Customer, CustomerDetailsViewModel>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street));
    /* etc, for other address properties */

就我个人而言,我不会太担心两次致电.Map.至少以这种方式,很明显,AddressCustomer属性都已被映射.

Personally, I wouldn't be too worried about calling .Map twice. At least that way it's very clear that both Address and Customer properties are being mapped.

这篇关于使用自动映射器映射嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆