http://jahav.com/blog/automapper-queryable-extensions/
How to generate a LINQ query for your DTOs
AutoMapper is a really cool library This 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 had to map them from one L Ayer to another, e.g. from business object to ViewModel.
All are good and well for POCO, not so much for entity objects. The AutoMapper tries to map everything using reflection and so properties like Project.code can turn to Projectcode is troublesome with ORM, where querying a 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 is nice to hav e a DTO type, entity type and magically create a LINQ expression mapping from one to another that can is used by Nhibernat e LINQ provider.
Remember, such expression would require only necessary fiels, so Id or Created won ' t is part of the SQL query (see NHibernate L INQ 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's no panacea, but it solves the most of my trouble.
Notice the key difference, normal automapping'll traverse object graph and return a mapped object, QE would only generate A mapping expression.
Example
I'll provide an example using the entities above:
- NuGet package AutoMapper for, the is part of the package and is in
QueryableExtensions
AutoMapper.QueryableExtensions
namespace
- Create a test
- Create a mapping
Mapper.CreateMap<Post, PostDto>();
- Query by hand (see query above)
var Postdto =
session. Query<post> (). Wherepost => Postid == Id) &NBSP;
. (). To<postdto> () &NBSP;
. Single
- Observe the generated SQL:
Select
Blog1_.Name Ascol_0_0_,
post0_.Title Ascol_1_0_,
post0_.Body Ascol_2_0_
From
Postpost0_
Left OUTER JOIN
blog blog1_
on Post0_.< Span class= "Typ" >blog=blog1_. Id
where&NBSP;
post0_ id= @p0 ; @p0 = 1 [type: Int32 (0&NBSP;
It is no different, the SQL generated by the hand made query. It is queries necessary without boilerplate code.
- Remove boilerplate code from your app.
You can also does a more difficult transformations, although QE is slightly more limited than in-memory AutoMapper Capabili Ties, go and read the wiki.
This was really cool extension that would remove quite a lot of boilerplate code and so give it a try!
AutoMapper queryable Extensions Find only the fields you need