C# AutoMapper 使用简易说明
AutoMapper 是 C# 中常用的第三方映射库,比如有下面两个类
public class 学生
{
public string 姓名 { get; set; }
public int 年龄 { get; set; }
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
假如,外部传进来(如走WebApi)的类是 Student ,而我们的软件的实体类是“学生”类,那么我想把 Student 转成 学生 类,则一般我们采用的方法如下
Student student = new Student() { Name = "张三", Age = 12 };
学生 xuesheng = new 学生()
{
姓名 = student.Name,
年龄 = student.Age
};
因为这个两个类比较简单,所以我们采用这种方法看起来完全没有问题,但是如果类的属性很多,或者有很多这样的类似的类需要转换,如果我们还是这种手动的赋值,那么简直就是hell。
这时,AutoMapper就能排上用场了。
步骤如下
1.通过nuget 引入AutoMapper
2.在项目根目录下建立 Profiles文件夹(注意一定要写对,否则采用依赖注入的方式AutoMapper自动加载配置信息扫不到该映射的),在下面新建一个StudentProfile.cs的类文件,代码如下
using AutoMapper;
public class StudentProfile: Profile
{
public StudentProfile()
{
CreateMap<Student, 学生>();
}
}
接下来有两种方式来使用上面的映射配置:
方法一:采用依赖注入 (此处以WPF为例)
使用依赖注入方式,需要额外从Nuget安装 AutoMapper.Extensions.Microsoft.DependencyInjection依赖库
依赖
public void ConfigureServices(IServiceCollection services)
{
//加载Profiles映射关系,自动查找Profiles文件夹下的映射类
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
......其他代码.....
}
注入
private IMapper _mapper { get; set; }
public MainWindowViewModel(IMapper mapper)
{
_mapper = mapper;
}
public void Test(Student student)
{
学生 xuesheng = New 学生();
_mapper.Map(student, xuesheng);
}
方法二:手动使用AutoMapper
Public Void Test ( Student student )
{
///手动加载映射关系
var configuration = new MapperConfiguration(cfg =>
{
cfg.AddProfile<Profiles.StudentProfile>();
});
///手动映射
var mapper = configuration.CreateMapper();
学生 xuesheng = mapper.Map<Student,学生>(student);
}