NetCore+AutoMapper多个对象映射到一个Dto对象
目录
一、定义源映射类和被映射类DTO
二、注入AutoMapper
三、配置映射
四、调用AutoMapper完成赋值
五、运行测试
一、定义源映射对象
为了体现AutoMapper映射特性,在SocialAttribute中的Name属性没有定义在People中,People的Ear属性也不存在与SocialAttribute和PhysicalAttribute中。
代码如下:
PhysicalAttribute
SocialAttribute
PeopleDto
二、注入AutoMapper
例子中使用的IOC容器是Autofac,不使用Autofac的话,仅用NetCore框架继承的IOC容器也可以实现。
注册AutoMapper必要组件:
复制代码
public static class AutoMapperInjection
{
public static ContainerBuilder LoadAutoMapper(this ContainerBuilder builder)
{
builder.RegisterType().SingleInstance();
builder.Register(m => {
var mapperConfigurationExpression = m.Resolve();
var instance = new MapperConfiguration(mapperConfigurationExpression);
return instance;
});
builder.Register(m => {
var mapperConfiguration = m.Resolve();
return mapperConfiguration.CreateMapper();
});
return builder;
}
}
复制代码
三、配置映射
ForMember:映射两个类之间的属性关系。
People类中的Ear属性并不存在于任何映射源类中,我们可以使用ForMember(m => m.Ear, n => n.Ignore())忽略该属性,当然也可以不写这段代码,对AutoMapper不会有任何影响,但是为了后期维护更方便,我比较习惯将Dto类的属性写全。
SocialAttribute类中的Name属性不存在与People类中,直接忽略它,Name也不会被AutoMapper赋值。
复制代码
public class AutoMapperProfile: Profile
{
public void Mapping(ILifetimeScope scope) {
var expression = scope.Resolve();
expression.CreateMap()
.ForMember(m => m.Eye, n => n.MapFrom(s => s.Eye))
.ForMember(m => m.Mouth, n => n.MapFrom(s => s.Mouth));
//.ForMember(m => m.Ear, n => n.Ignore());
expression.CreateMap()
.ForMember(m => m.Age, n => n.MapFrom(s => s.Age))
.ForMember(m => m.IsMarried, n => n.MapFrom(s => s.IsMarried));
}
}
复制代码
四、调用AutoMapper完成赋值
调用AutoMapper,将PhysicalAttribute和SocialAttribute的值赋给PeopleDto
复制代码
public class DtoHelper
{
private IMapper mapper;
public DtoHelper(IMapper _mapper) {
mapper = _mapper;
}
public PeopleDto GetDto(PhysicalAttribute physical,SocialAttribute social) {
PeopleDto peopleDto = new PeopleDto();
mapper.Map(social, mapper.Map(physical, peopleDto));
return peopleDto;
}
}
复制代码
五、运行测试
测试框架使用的xUnit
复制代码
public class DtoHelperTest
{
[Fact]
public void GetDto() {
//moke
ContainerBuilder builder = new ContainerBuilder();
builder.LoadAutoMapper();
builder.RegisterType();
IContainer Container = builder.Build();
using (var scope = Container.BeginLifetimeScope())
{
scope.Resolve().Mapping(scope);
PeopleDto result = new PeopleDto() { Eye = "双眼皮", Mouth = "红润", Age = 18, IsMarried = false };
PhysicalAttribute physical = new PhysicalAttribute() { Eye = "双眼皮", Mouth = "红润" };
SocialAttribute social = new SocialAttribute() { Name = "张三", IsMarried = false, Age = 18 };
PeopleDto output = new DtoHelper(scope.Resolve()).GetDto(physical, social);
//Assert.Same(result, output);
Assert.Equal(JsonConvert.SerializeObject(result), JsonConvert.SerializeObject(output));
}
}
}
复制代码
通过测试!
参考项目:https://github.com/FB208/CodeSpace/tree/master/CodeSpace.CSharp/WebMvc/DemoClass/AutoMapperDemohttps://www.cnblogs.com/fb208/p/11548250.html