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. asp.net MVC中防止跨站请求攻击(CSRF)的ajax用法

    参考: Preventing Cross-Site Request Forgery (CSRF) AttacksValidating .NET MVC 4 anti forgery tokens in ...

  2. CDbConnection failed to open the DB connection: could not find driver错误的处理

    在PHP.INI文件中extension=php_pdo_mysql.dll 去掉注释

  3. docker machine介绍和使用

    https://www.cnblogs.com/sparkdev/p/7044950.html https://www.jianshu.com/p/cc3bb8797d3b

  4. 使用editorconfig配置你的编辑器

    摘要: 在团队开发中,统一的代码格式是必要的.但是不同开发人员使用的编辑工具可能不同,这样就造成代码的differ.今天给大家分享一个很好的方法来使不同的编辑器保持一样的风格. 不同的编辑器也有设置代 ...

  5. 使用pycharm,追求最优的代码。

    1.最近追求的是代码0警告,没有任何提示. 怎么追求这样的目标,不需要再去单独使用pylint和flake8这些玩意,只需要看pycharm右边编辑区的竖向滚动条的黄色就可以了. 2. 比较糟糕的就是 ...

  6. [Scikit-learn] 1.1 Generalized Linear Models - Lasso Regression

    Ref: http://blog.csdn.net/daunxx/article/details/51596877 Ref: https://www.youtube.com/watch?v=ipb2M ...

  7. [Unity3D] 01 - Try Unity3D

    01. Move and Rotate 标准全局坐标系 Keyboard using UnityEngine; using System.Collections; public class NewBe ...

  8. Ubuntu14.04下Mongodb(离线安装方式|非apt-get)安装部署步骤(图文详解)(博主推荐)

    不多说,直接上干货! 说在前面的话  首先,查看下你的操作系统的版本. root@zhouls-virtual-machine:~# cat /etc/issue Ubuntu LTS \n \l r ...

  9. Weblogic集群部署

    有些事情不去尝试,注定是失败,如果预知90%的失败仍然去尝试了,那也会从中学到很多,何况仅靠那10%的可能性也会成功 weblogic安装后 1.打开Configuration Wizard 2.创建 ...

  10. linux给当前用户添加环境变量

    比如当前用户为oracel,则添加环境变量操作为: vim  /home/oracel/.bashrc