且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用自动映射器映射嵌套对象

更新时间:2022-02-24 23:08:21

这取决于您的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.