特性映射 (Attribute Mapping)
除了使用流式 API 来实现映射, 还可以通过 Attribute 来实现映射. 特性映射可以补充, 甚至是替换流式 API 映射.
类型映射配置
实现步骤:
- 创建配置, 调用
AddMaps()
方法, 用于定义搜索程序集. - 在目标类型上定义
AutoMap
特性, 指定源类型的Type
.
var conf = new MapperConfiguration(cfg => cfg.AddMaps("MyAssembly"));
var mapper = new Mapper(conf);
AddMaps
会插值程序集中的 Profile
类型, 以及基于特性的映射.
使用时:
[AutoMapper(typeof(Order))]
public class OrderDto {
...
}
自定义类型映射配置
通过 AutoMapAttribute
设置下列属性, 来自定义类型映射
ReverseMap
(bool
)ConstructUsingServiceLocator
(bool
)MaxDepth
(int
)PreserveReferences
(bool
)DisableCtorValidation
(bool
)IncludeAllDerived
(bool
)TypeConverter
(Type
)AsProxy
(bool
)
其中必须的参数只有 sourceType
.
成员配置
特性与流式 API 各有优势, 限于语法特性的原因, 特性映射无法处理所有情况, 必要时需要根据 Profile
结合使用.
基于特性的成员被定义在 AutoMapper.Configuration.Annotations
命名空间下.
忽略成员
需要忽略某个属性映射, 在属性上使用 [Ignore]
即可.
using AutoMapper.Configuration.Annotations;
[AutoMap(typeof(Order))]
public class OrderDto {
[Ignore]
public decimal Total { get; set; }
重定向到不同源的类型成员
特性映射无法使用 MapFrom
, 但是有 SourceMemberAttribute
可以使用
using AutoMapper.Configuration.Annotations;
[AutoMap(typeof(Order))]
public class OrderDto {
[SourceMember("OrderTotal")]
public decimal Total { get; set; }
或使用 nameof
using AutoMapper.Configuration.Annotations;
[AutoMap(typeof(Order))]
public class OrderDto {
[SourceMember(nameof(Order.OrderTotal))]
public decimal Total { get; set; }
无法使用特性扁平化, 只能重定向. 扁平化只能用流式 API 实现.
附加配置选项
每一个都有对应的 流式 API.
MapAtRuntimeAttribute
MappingOrderAttribute
NullSubstituteAttribute
UseExistingValueAttribute
ValueConverterAttribute
ValueResolverAttribute