Profile purpose: Extract a large number of mapping rules into a standalone class instead of cramming them all into the Main method, making it easier to manage mappings for multiple entities.
1. Custom Profile Class
Inherit from AutoMapper’s Profile base class, define mapping rules inside the constructor, and write multiple CreateMap statements at once.
using AutoMapper;
/// <summary>
/// Mapping configuration class
/// </summary>
public class MappingProfile : Profile
{
public MappingProfile()
{
// Person → People
CreateMap<Person, People>();
// People → Person (bidirectional mapping)
CreateMap<People, Person>();
}
}
// [Code block Chinese translation]
// 映射配置类
// Person → People
// 双向映射
Code language: HTML, XML (xml)
Method 1: Add Profile during initialization
Mapper.Initialize(x => x.AddProfile<MappingProfile>());
Code language: JavaScript (javascript)
Method 2: Full syntax, instantiate Profile object
var mc = new MapperConfigurationExpression();
mc.AddProfile(new MappingProfile());
Mapper.Initialize(mc);
// [Code block Chinese translation]
// 实例化Profile对象
Code language: JavaScript (javascript)
2. Loading Multiple Profiles
When the project grows complex, you’ll split mappings into multiple Profile classes. You can register them all at once:
Mapper.Initialize(x =>
{
x.AddProfile<MappingProfile>();
x.AddProfile<MappingProfile2>();
});
Code language: HTML, XML (xml)
Complete Program Example
class Program
{
static void Main(string[] args)
{
// ========= Configuration: Load Profile mapping =========
Mapper.Initialize(x => x.AddProfile<MappingProfile>());
// Source object, target object
Person p = new Person()
{
Age = 12,
Name = "Tom",
Birthday = DateTime.Now,
Sex = true,
Salary = 10000
};
People peo = new People()
{
Age = 36,
Name = "Jack",
Birthday = DateTime.Now,
Sex = true,
Salary = 102000
};
// Forward mapping Person → People
Mapper.Map(p, peo);
// Reverse mapping People → Person
Mapper.Map(peo, p);
Console.WriteLine(peo.Name);
Console.WriteLine(p.Name);
Console.ReadKey();
}
}
// [Code block Chinese translation]
// 配置:加载Profile映射
// 源对象、目标对象
// 正向映射 Person → People
// 反向映射 People → Person
Code language: JavaScript (javascript)
Configure Profile
Previous: Install and the first example
Next: Flattening Mapping