控制台程序为例,展示该demo
一、安装Nuget包
二、文件结构
三、AutoMapperProfile.cs(映射规则)
using AutoMapper;
namespace ConsoleApp1
{
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<Student, Teacher>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name));//配置不同名的字段映射
//其他字段:字段名称一样的自动映射
}
}
}
四、Model.cs(实体模型)
namespace ConsoleApp1
{
public class Model
{
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class Teacher
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}
}
五、Program.cs(程序入口)
using AutoMapper;
namespace ConsoleApp1
{
internal class Program
{
static void Main(string[] args)
{
// 配置规则
var configuration = new MapperConfiguration(cfg =>
{
cfg.AddProfile<AutoMapperProfile>();
});
// 创建映射器
IMapper mapper = configuration.CreateMapper();
// 创建学生实体
var student = new Student
{
Id = 1,
Name = "小苏",
Age = 20
};
// 映射成老师
var teacher = mapper.Map<Teacher>(student);
Console.WriteLine($"Teacher: Id={teacher.Id}, FullName={teacher.FullName}, Age={teacher.Age}");
//输出:Teacher: Id=1, FullName=小苏, Age=20
}
}
}