AutoMapper query able extensions 필요 한 필드 만 찾 습 니 다.
6108 단어 mapper
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:
QueryableExtensions
are part of the package and are in AutoMapper.QueryableExtensions
namespace Mapper.CreateMap<Post, PostDto>();
var postDto =
session.Query<Post>().Where(post => post.Id == id)
.Project().To<PostDto>()
.Single();
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. 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!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
간단한 AutoMapper를 사용한 DTO 변환DTO(Data Transfer Object) 데이터 전송 대상은 데이터만 전송하고 영역 대상과의 전환을 완성하며 영역 업무 처리를 포함하지 않는다.DTO는 영역 모델 설계자가 핵심 업무에만 집중하고 영역 모델의 정...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.