繁体   English   中英

组连接导致IQueryable变成IEnumerable,为什么?

[英]Group join causes IQueryable to turn into IEnumerable, why?

我正在访问远程数据源,发现组连接导致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
    })

    });

行:.GroupJoin( _abilities ,x => x.eProfile.ID,y => y.ID, (x,y) => new QuoteDTO

  1. _abilities是一个IQueryable,我得到了用户的能力,一个对象的集合
  2. 第二部分(x,y) - 这里y被转换成IEnumerable ......

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));

注意:我使用var的原因是我可以转换成我喜欢的对象,在插入DTO对象之前我使用了很多匿名类型...

IQueryable的定义:

public interface IQueryable<T> : IEnumerable<T>, IQueryable, IEnumerable

...和ObjectQuery:

ObjectQuery<T> : ObjectQuery, IOrderedQueryable<T>, IQueryable<T>, IEnumerable<T>, IOrderedQueryable, IQueryable, IEnumerable, IListSource

大多数(所有?)LINQ表达式返回一个强制转换为IEnumerable的对象。 但是对象的类型仍然是它开始的类型。

不,当LINQ-to-Entities查询被强制转换为IEnumerable时,数据库不会被命中,因此性能不会受到影响。 如果您愿意,您可以向上转换为IQueryable或ObjectQuery。

编辑:为了澄清,在ObjectQuery,IQueryable或IEnumerable的实例上调用ToArray()确实命中数据库并检索结果集。

编辑:在查询中创建一个新对象(即新的QuoteDTO)将命中数据库,因为没有办法将新对象存储在SQL查询中。 对不起,我以前错过了那一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM