自动映射器从嵌套类映射到单个(拼合) [英] Automapper map from nested class to single (flatten)

查看:80
本文介绍了自动映射器从嵌套类映射到单个(拼合)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的出处:

public class User
{
    public int UserId { get; set; }

    public Address Address { get; set; }
}

public class Address
{
    public string Address { get; set; }
    public string State {get; set; }
}

这是我的目的地:

public class UserVM
{
    public int UserId { get; set; }

    public string Address { get; set; }
    public string State { get; set; }
}

如何进行映射?当他们说展平是自动的时,普通的创建贴图不起作用.

How do I do the mapping? The normal create map doesn't work when they say flattening is automatic.

推荐答案

如果将目标类的属性名称更改为AddressStreetAddressState,则AutoMapper将按照约定将它们与Address.StreetAddress.State匹配.在源头上.

If you change your destination class property names to AddressStreet and AddressState, AutoMapper will, by convention, match them to Address.Street and Address.State on the source.

public class UserVM
{
    public int UserId { get; set; }

    public string AddressStreet { get; set; } // User.Address.Street
    public string AddressState { get; set; }  // User.Address.State
}

或者,您保留目标属性名称不变,并使用自定义成员映射:

Alternatively, you leave your destination property names as is and use custom member mappings:

Mapper.CreateMap<User, UserVM>()
    .ForMember(dest => dest.Street, opt => opt.MapFrom(src => src.Address.Street))
    .ForMember(dest => dest.State, opt => opt.MapFrom(src => src.Address.State));

有关 Projection

See the AutoMapper documentation for Projection and Flattening for more information.

这篇关于自动映射器从嵌套类映射到单个(拼合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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