AutoMapper - 将源对象映射到嵌套对象

AutoMapper - Map source object to nested object

如何将单个对象映射到嵌套对象?

下图是我的实体

class Employee
{
    public string name { get; set; }
    public string city_name { get; set; }
    public string State_name { get; set; }
}

我想映射到

class Employee
{
    public string Name;
    public Location Location;
}

class Location
{
    public string City;

    public string State;
}

请注意 属性 名称不同。任何人都可以使用 AutoMapper 帮助映射这些吗?

解决方案 1:ForPath

1.1 创建 Profile 继承自 Profile 的实例,并将配置放在构造函数中。

1.1.1 使用 ForPath 映射嵌套 属性.

public class EmployeeProfile : Profile
{
    public EmployeeProfile()
    {
        CreateMap<Employee, EmployeeDto>()
            .ForPath(dest => dest.Location.City, opt => opt.MapFrom(src => src.city_name))
            .ForPath(dest => dest.Location.State, opt => opt.MapFrom(src => src.State_name));
    }
}

1.2 将配置文件添加到映射器配置

public static void Main()
{
    var config = new MapperConfiguration(cfg =>
    {

        cfg.AddProfile<EmployeeProfile>();

        // Note: Demo program to use this configuration rather with EmployeeProfile
        /*
        cfg.CreateMap<Employee, EmployeeDto>()
            .ForPath(dest => dest.Location.City, opt => opt.MapFrom(src => src.city_name))
            .ForPath(dest => dest.Location.State, opt => opt.MapFrom(src => src.State_name));
        */      
    });
    IMapper mapper = config.CreateMapper();
        
    var employee = new Employee{name = "Mark", city_name = "City A", State_name = "State A"};

    var employeeDto = mapper.Map<Employee, EmployeeDto>(employee);
}

Sample Solution 1 on .Net Fiddle


解决方案 2:AfterMap

2.1 创建 Profile 继承自 Profile 的实例,并将配置放在构造函数中。

2.1.1使用AfterMap在映射发生后执行嵌套映射属性。

public class EmployeeProfile : Profile
{
    public EmployeeProfile()
    {
        CreateMap<Employee, EmployeeDto>()
            .AfterMap((src, dest) => { dest.Location = 
                    new Location {
                        City = src.city_name,
                        State = src.State_name
                    };
                });
    }
}

2.2 将配置文件添加到映射器配置

public static void Main()
{
    var config = new MapperConfiguration(cfg =>
    {

        cfg.AddProfile<EmployeeProfile>();

        // Note: Demo program to use this configuration rather with EmployeeProfile
        /*
        cfg.CreateMap<Employee, EmployeeDto>()
            .AfterMap((src, dest) => { dest.Location = 
                    new Location {
                        City = src.city_name,
                        State = src.State_name
                    };
                });
        */      
    });
    IMapper mapper = config.CreateMapper();
        
    var employee = new Employee{name = "Mark", city_name = "City A", State_name = "State A"};

    var employeeDto = mapper.Map<Employee, EmployeeDto>(employee);
}

Sample Solution 2 on .Net Fiddle


参考资料

  1. ForPath
  2. Profile Instances
  3. Before and After Map