AutoMapper 设置
var config = new MapperConfiguration(cfg => {
cfg.AddProfile<AppProfile>(); // 添加配置文件
cfg.CreateMap<Source, Dest>(); // 创建源到目标的映射
});
var mapper = config.CreateMapper();
// 或者
IMapper mapper = new Mapper(config);
var dest = mapper.Map<Source, Dest>(new Source()); // 执行映射
提示
从 9.0 版本开始,静态 API 不再可用。
初始化前收集配置
AutoMapper 也允许你在初始化前收集配置信息:
var cfg = new MapperConfigurationExpression();
cfg.CreateMap<Source, Dest>(); // 创建映射
cfg.AddProfile<MyProfile>(); // 添加配置文件
MyBootstrapper.InitAutoMapper(cfg); // 初始化AutoMapper
var mapperConfig = new MapperConfiguration(cfg);
IMapper mapper = new Mapper(mapperConfig); // 创建映射器实例
LINQ 投影
对于实例 API,你可以使用 IMapper.ProjectTo
来进行 LINQ 投影。如果你更倾向于继续使用 IQueryable
的扩展方法,则需要传递 MapperConfiguration
实例:
public class ProductsController : Controller {
public ProductsController(MapperConfiguration config) {
this.config = config; // 存储配置实例
}
private MapperConfiguration config;
public ActionResult Index(int id) {
var dto = dbContext.Products // 执行数据库查询并进行投影
.Where(p => p.Id == id)
.ProjectTo<ProductDto>(config)
.SingleOrDefault();
return View(dto);
}
}
不支持的操作
AutoMapper 的一个“特性”是允许你在运行时修改配置。这导致了许多问题,因此新 API 不允许你这样做。你需要将所有 Mapper.CreateMap
调用移入配置文件中。
动态映射,如 Mapper.DynamicMap
,不再被支持。