http://jahav.com/blog/automapper-queryable-extensions/

How to generate a LINQ query for your DTOs

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:

  1. NuGet package for AutoMapper, the QueryableExtensions are part of the package and are in AutoMapper.QueryableExtensions namespace
  2. Create a test
  3. Create a mapping
    Mapper.CreateMap<Post, PostDto>();
  4. Query by hand (see query above)
    var postDto =  
       session.Query<Post>().Where(post => post.Id == id) 
       .Project().To<PostDto>() 
       .Single();
  5. 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.

  6. 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!

AutoMapper queryable extensions 只找需要的字段的更多相关文章

  1. 16.AutoMapper 之可查询扩展(Queryable Extensions)

    https://www.jianshu.com/p/4b23e94a7825 可查询扩展(Queryable Extensions) 当在像NHibernate或者Entity Framework之类 ...

  2. aufomaper Queryable Extensions ProjectTo

    When using an ORM such as NHibernate or Entity Framework with AutoMapper's standard Mapper.Map funct ...

  3. thinkphp 找数据库某个字段为空的数据,PHP 数据调取 空数据

    $arr['dingwei'] = array('EXP','is null');

  4. EF只更新变化的字段

    摘要 在使用EF的时候,由于表字段较多,所以在更新的时候,想要只更新变化的字段,有没有办法呢? 解决办法 代码片段 public async Task<int> UpdateAsync(T ...

  5. 转 A 、B两张表,找出ID字段中,存在A表,但是不存在B表的数据

    A.B两张表,找出ID字段中,存在A表,但是不存在B表的数据,A表总共13W数据,去重后大约3万条数据,B表有2W条数据,且B表的ID有索引. 方法一 使用not in,容易理解,效率低. selec ...

  6. PDF.NET+EasyUI实现只更新修改的字段

    PDF.NET 在我看来是目前最简单易用而且高效的orm框架之一,感谢作者深蓝医生 实现的功能是easyui的行内编辑,用到了爱看书不识字的datagrid仿extjs的行内编辑 都是牛人啊. 201 ...

  7. asp.net mvc 不找其他view模板,只找cshtml

    asp.net mvc 默认找view文件时,依次找后辍名为aspx.ascx.cshtml.vbhtml的view文件.但是项目住住用C#+Razor开发,这样找,岂不有性能损失. 添加以下代码: ...

  8. Hibernate高效查询,只查询部分/指定字段

    公司使用 DetachedCriteria detachedCriteria = DetachedCriteria.forClass(PeBulletin.class); detachedCriter ...

  9. 如何只更新datetime类型字段中的日期

    UPDATE  [dbo].[Order]       SET     CreateDate = STUFF(CONVERT(VARCHAR(50),CreateDate,126) ,1, 10, ' ...

随机推荐

  1. Android图片编码机制深度解析(Bitmap,Skia,libJpeg)

    问题 工作中遇到了Android中有关图片压缩保存的问题,发现这个问题还挺深,而且网上资料比较有限,因此自己深入研究了一下,算是把这个问题自顶至下全部搞懂了,在此记录. 相关的几个问题如下: 1.An ...

  2. EJB的魅惑来源

      有人发帖子问学习EJB有个屁用啊?看完下面一个简单的介绍,也许你对EJB很感兴趣,它的优点极具魅惑力. 一.EJB是基于组件的开发. 利用Enterprise JavaBean,你就能像搭积木一样 ...

  3. 内存管理 初始化(五)kmem_cache_init 初始化slab分配器(上)

    看了下kmem_cache_init,涉及到不同MIGRATE间的buddy system的迁移,kmem_cache的构建,slab分配器头的构建.buddy system的伙伴拆分. 对于SMP系 ...

  4. iOS多版本多设备适配的问题

    好吧,能找到这文章的,一般是接到了如下需求:  我是从raywenderlich抽了点内容出来做日记,另外,本文说的不是布局的适配,而是因为ios的升级带来的各版本代码上的不兼容. Deploymen ...

  5. Node.js之操作Mongodb

    // mongoose 链接 var mongoose = require('mongoose'); var db = mongoose.createConnection('mongodb://127 ...

  6. 【QT】Cannot find file: untitled.pro,项目路径不要包含中文。

    Cannot find file: D:\文件及下载相关\文档\untitled\untitled.pro. 17:01:45: 进程"D:\Englishpath\QT5.9.3\5.9. ...

  7. JSP求和计算

    已知两个数的值,如何求和并输出? <%@ page language="java" import="java.util.*,java.text.*" co ...

  8. 添加额外的源, 使得yum可以安装更多的软件

    RHEL 官方扩展源 yum localinstall http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch. ...

  9. elastic search 概念

    1. index 与 type index 相当于 mysql 的 database, type 相当于 table 2. mapping mapping 相当于 mysql table 的列属性声明 ...

  10. Java最快的maven仓库地址,国内Maven地址,超快的Maven地址

    Java最快的maven地址,国内Maven地址,超快的Maven地址 >>>>>>>>>>>>>>>> ...