解决方案 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在map发生后使用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
参考文献
ForPath
- Profile Instances
- Before and After Map