Har*_*oon 7 c# iqueryable linq-to-sql
我正在访问远程数据源,发现组连接导致IQueryable查询转换为IEnumerable,
问题:这会影响性能吗?我想尽可能多地将查询卸载到数据库中,而不是在内存中执行任何操作......
var allusers = repo.All<User>().Where(x => x.IsActive);
var _eprofile = repo.All<Profile>()
.Where(x => x.IsProfileActive)
.Join(allusers, x => x.UserID, y => y.UserID, (x, y) => new
{
eProfile = x,
profile = y
})
.GroupJoin(_abilities, x => x.eProfile.ID, y => y.ID, (x, y) => new QuoteDTO
{
UserID = x.profile.Login,
Email = x.profile.Email,
Tel = x.profile.Tel,
Mobile = x.eProfile.Mobile,
CompanyID = x.profile.CompanyID,
Ability = y.Select(c => new AbilityDTO
{
Name= c.Name
})
});
Run Code Online (Sandbox Code Playgroud)
行:.GroupJoin(_abilities,x => x.eProfile.ID,y => y.ID,(x,y) => new QuoteDTO
var cLists = List<int>(); //这个集合是从客户端代码中填充的,假设//为了参数而包含1,3,55 ...
var _abilities= repo.All<UserAbility>()
.Where(x => x.Status == Status.Active.ToString())
.Where(x => cLists.Contains(x.CompetencyID));
Run Code Online (Sandbox Code Playgroud)
注意:我使用var的原因是我可以转换成我喜欢的对象,在插入DTO对象之前我使用了很多匿名类型...
IQueryable的定义:
public interface IQueryable<T> : IEnumerable<T>, IQueryable, IEnumerable
Run Code Online (Sandbox Code Playgroud)
...和对象查询:
ObjectQuery<T> : ObjectQuery, IOrderedQueryable<T>, IQueryable<T>, IEnumerable<T>, IOrderedQueryable, IQueryable, IEnumerable, IListSource
Run Code Online (Sandbox Code Playgroud)
大多数(全部?)LINQ 表达式返回一个转换为 IEnumerable 的对象。但对象的类型仍然是它开始时的类型。
不会,当 LINQ-to-Entities 查询转换为 IEnumerable 时,数据库不会被命中,因此性能不会受到影响。如果您愿意,您可以向上转换为 IQueryable 或 ObjectQuery。
编辑:为了澄清,在 ObjectQuery、IQueryable 或 IEnumerable 实例上调用 ToArray() 确实会访问数据库并检索结果集。
编辑:在查询中创建新对象(即新的 QuoteDTO)将访问数据库,因为无法将新对象存储在 SQL 查询中。抱歉,我之前错过了这一点。
| 归档时间: |
|
| 查看次数: |
1880 次 |
| 最近记录: |