博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
静态和实例初始化映射
阅读量:5901 次
发布时间:2019-06-19

本文共 2072 字,大约阅读时间需要 6 分钟。

In 4.2.1 version of AutoMapper and later, AutoMapper provides two APIs: a static and an instance API. The static API:

Mapper.Initialize(cfg => {    cfg.AddProfile
(); cfg.CreateMap
();});var dest = Mapper.Map
(new Source());

And the instance API:

var config = new MapperConfiguration(cfg => {    cfg.AddProfile
(); cfg.CreateMap
();});var mapper = config.CreateMapper();// orIMapper mapper = new Mapper(config);var dest = mapper.Map
(new Source());

Gathering configuration before initialization

AutoMapper also lets you gather configuration before initialization:

var cfg = new MapperConfigurationExpression();cfg.CreateMap
();cfg.AddProfile
();MyBootstrapper.InitAutoMapper(cfg);Mapper.Initialize(cfg);// orvar mapperConfig = new MapperConfiguration(cfg);IMapper mapper = new Mapper(mapperConfig);

LINQ projections

For the instance method of using AutoMapper, LINQ now requires us to pass in the MapperConfiguration instance:

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
(config) .SingleOrDefault(); return View(dto); } }

Unsupported operations

One "feature" of AutoMapper allowed you to modify configuration at runtime. That caused many problems, so the new static API does not allow you to do this. You'll need to move all your Mapper.CreateMap calls into a profile, and into a Mapper.Initialize.

For dynamic mapping, such as Mapper.DynamicMap, you can configure AutoMapper to create missing maps as needed:

Mapper.Initialize(cfg => cfg.CreateMissingTypeMaps = true);

Internally this uses conventions to create maps as necessary.

转载于:https://www.cnblogs.com/Leman/p/5774383.html

你可能感兴趣的文章
MongoDB经典面试题集锦
查看>>
四、System Center Virtual Machine Manager 2012 添加Citrix Xenserver 6.0主机
查看>>
Google Glass是工具不是玩具
查看>>
Asp.Net MVC4入门指南(10):第三方控件Studio for ASP.NET Wijmo MVC4 工具应用
查看>>
SharePoint 2010整合Silverlight 4应用 - 任务管理
查看>>
javascript 字符串操作 自定义函数
查看>>
安装配置vsftp
查看>>
手机辐射对人体健康没有危害
查看>>
AutoLISP查询椭圆的相关属性
查看>>
论修改系统默认的jdk
查看>>
处理文章附件路径问题
查看>>
Asp.net"页面加载中"效果实现
查看>>
C++类属性算法search
查看>>
2011/6/26 功能菜单模块分析
查看>>
25佳漂亮的网站底部设计案例欣赏
查看>>
中国象棋运动发展之我见
查看>>
ECMAScript旮里旮旯儿一(galigalaoer)
查看>>
【黑金视频连载】NIOSII视频教程(06)--沿中断实验
查看>>
HDU-2094 产生冠军
查看>>
poj1015
查看>>