AutoMapper queryable extensions 只找需要的字段
2015-07-19 09:34
316 查看
AutoMapper is a really cool library that allows us to map one object to another, e.g. when passing objects through layers of our application, where we work with different objects in different layers of our app and we have to map them from one layer to another, e.g. from business object to viewmodel.
All is good and well for POCO, not so much for entity objects. The automapper tries to map everything using reflection, so properties like Project.Code can turn to ProjectCode, but that is troublesome with ORM, where querying an object means loading another entity from the database.
I am using a NHibernate linq provider that only gets columns we actually ask from the database, so it would be nice to have a DTO type, entity type and magically create a linq expression mapping from one to another that can be used by NHibernate LINQ provider.
Remember, such expression will require only necessary fiels, so Id or Created won’t be part of SQL query (see NHibernate Linq query evaluation process for more info).
Queryable Extensions
Automapper provides a solution to this proble: queryable extensions (QE). They allow us to create such expression and they even solve SELECT N+1 problem. It is no panacea, but it solves most of my trouble.Notice the key difference, normal automapping will traverse object graph and return a mapped object, QE will only generate a mapping expression.
Example
I will provide an example using the entities above:NuGet package for AutoMapper, the
QueryableExtensionsare part of the package and are in
AutoMapper.QueryableExtensionsnamespace
Create a test
Create a mapping
Mapper.CreateMap<Post, PostDto>();
Query by hand (see query above)
var postDto = session.Query<Post>().Where(post => post.Id == id) .Project().To<PostDto>() .Single();
Observe the generated SQL:
select blog1_.Name as col_0_0_, post0_.Title as col_1_0_, post0_.Body as col_2_0_ from Post post0_ left outer join Blog blog1_ on post0_.Blog=blog1_.Id where post0_.Id=@p0; @p0 = 1 [Type: Int32 (0)]
It is no different that the SQL generated by the hand made query. It only queries what is necessary without boilerplate code.
Remove boilerplate code from your app.
You can also do a more difficult transformations, although QE are slightly more limited than in-memory AutoMapper capabilities, go and read the wiki.
This is really cool extension that will remove quite a lot of boilerplate code, so give it a try!
相关文章推荐
- android如何提高加载布局页面速度
- Node.js项目3文件(view,app,routes)关系
- Android Fragment
- Android之——Handler随笔
- cocos2d-x-3.1.1工程创建
- android颜色值的表示方法android:background="#FFFFFFFF"的意思
- Android GridView一些错误
- Android应用程序启动过程
- 正确退出一个App的方法
- Android 使用NineOldAndroids实现仿微信listview左滑出现删除itembutton
- Android:TextView属性大全
- ioS开发零基础教程之支付宝支付iOS开发
- iOS动画之模拟音量振动条
- iOS敏捷开发之道,常用的宏定义总结
- iOS动画之漂亮的时钟
- AppStore中使用IDFA后提交应用的注意事项
- Android SnackBar:你值得拥有的信息提示控件
- Android SnackBar:你值得拥有的信息提示控件
- android 无标题栏的设置方法
- Android studio 1.3 NDK开发