概念
默认AutoMapper除了同名属性映射,还有扁平化映射规则:
如果源对象(Person)没有目标对象(People)的对应属性,AutoMapper会自动:
- 拆分源对象里面嵌套对象的属性:
Cn.Name→ 目标CnName- 匹配源对象中以
Get开头的无参方法:GetTotal()→ 目标属性Total
完整代码
using AutoMapper;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//初始化AutoMapper配置
Mapper.Initialize(x =>
{
x.CreateMap<Person, People>();
});
//源对象 Person
Person p = new Person()
{
Age = 12,
Cn = new Chinese() { Name = "Jack Chan" },
Birthday = DateTime.Now,
Sex = true,
Salary = 5000
};
People peo = new People();
//执行映射
Mapper.Map(p, peo);
Console.WriteLine(peo.CnName); //输出:Jack Chan 【扁平化:Cn.Name → CnName】
Console.WriteLine(peo.Total); //输出:100 【扁平化:GetTotal() → Total】
Console.ReadKey();
}
}
//源类
class Person
{
public int Age { get; set; }
//嵌套对象
public Chinese Cn { get; set; }
public decimal Salary { get; set; }
public bool Sex { get; set; }
public DateTime Birthday { get; set; }
//Get开头无参方法,自动映射到Total属性
public decimal GetTotal()
{
return 100M;
}
}
public class Chinese
{
public string Name { get; set; }
}
//目标类
class People
{
public int Age { get; set; }
//扁平化得到:嵌套对象Cn的Name,拼接成CnName
public string CnName { get; set; }
public decimal Salary { get; set; }
public bool Sex { get; set; }
public DateTime Birthday { get; set; }
//扁平化得到:匹配源的GetTotal()方法
public decimal Total { get; set; }
}
}Code language: JavaScript (javascript)
总结
- 嵌套对象属性拼接
源:Person.Cn.Name
目标属性叫CnName
AutoMapper自动把嵌套对象Cn+Name拼接,赋值给CnName。不需要手动写ForMember配置。 - 匹配Get开头的无参方法
源里面方法:public decimal GetTotal()
目标属性:public decimal Total
去掉Get前缀,方法返回值自动赋值给Total。
注意:方法必须无参数,才会触发这个扁平化规则。
输出
Jack Chan
100