簡體   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