AutoMapper是否支持Linq? [英] Does AutoMapper support Linq?
问题描述
我对具有延迟加载功能的Linq to SQL非常感兴趣.在我的项目中,我使用AutoMapper将数据库模型映射到域模型(从DB_RoleInfo
到DO_RoleInfo
).在我的存储库代码中,如下所示:
I am very interested in Linq to SQL with Lazy load feature. And in my project I used AutoMapper to map DB Model to Domain Model (from DB_RoleInfo
to DO_RoleInfo
). In my repository code as below:
public DO_RoleInfo SelectByKey(Guid Key)
{
return SelectAll().Where(x => x.Id == Key).SingleOrDefault();
}
public IQueryable<DO_RoleInfo> SelectAll()
{
Mapper.CreateMap<DB_RoleInfo, DO_RoleInfo>();
return from role in _ctx.DB_RoleInfo
select Mapper.Map<DB_RoleInfo, DO_RoleInfo>(role);
}
SelectAll
方法运行良好,但是当我调用SelectByKey
时,出现错误:
SelectAll
method is run well, but when I call SelectByKey
, I get the error:
方法"RealMVC.Data.DO_RoleInfo MapDB_RoleInfo,DO_RoleInfo"无法转换为SQL.
Method "RealMVC.Data.DO_RoleInfo MapDB_RoleInfo,DO_RoleInfo" could not translate to SQL.
Automapper是否不完全支持Linq?
Is it that Automapper doesn't support Linq completely?
我尝试使用以下手动映射代码代替Automapper:
Instead of Automapper, I tried the manual mapping code below:
public IQueryable<DO_RoleInfo> SelectAll()
{
return from role in _ctx.DB_RoleInfo
select new DO_RoleInfo
{
Id = role.id,
name = role.name,
code = role.code
};
}
此方法以我想要的方式工作.
This method works the way I want it to.
推荐答案
在撰写本文时,@ Aaronaught的答案是正确的,因为世界经常发生变化,而AutoMapper也随之变化.同时,在代码库中添加了 QueryableExtensions
,该代码库增加了对要翻译的投影的支持到表达式,最后是SQL.
While @Aaronaught's answer was correct at the time of writing, as often the world has changed and AutoMapper with it. In the mean time, QueryableExtensions
were added to the code base which added support for projections that get translated into expressions and, finally, SQL.
核心扩展方法是ProjectTo
1 .这是您的代码如下所示:
The core extension method is ProjectTo
1. This is what your code could look like:
using AutoMapper.QueryableExtensions;
public IQueryable<DO_RoleInfo> SelectAll()
{
Mapper.CreateMap<DB_RoleInfo, DO_RoleInfo>();
return _ctx.DB_RoleInfo.ProjectTo<DO_RoleInfo>();
}
,它的行为就像手动映射一样. (这里的CreateMap
语句用于演示.通常,在应用程序启动时定义一次映射.)
and it would behave like the manual mapping. (The CreateMap
statement is here for demonstration purposes. Normally, you'd define mappings once at application startup).
因此,仅查询映射所需的列,结果是IQueryable
,该IQueryable
仍具有原始查询提供程序(linq-to-sql,linq-to-entities等).因此它仍然是可组合的,它将转换为SQL中的WHERE
子句:
Thus, only the columns that are required for the mapping are queried and the result is an IQueryable
that still has the original query provider (linq-to-sql, linq-to-entities, whatever). So it is still composable and this will translate into a WHERE
clause in SQL:
SelectAll().Where(x => x.Id == Key).SingleOrDefault();
4.1.0之前的
1 Project().To<T>()
1 Project().To<T>()
prior to v. 4.1.0
这篇关于AutoMapper是否支持Linq?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!