簡體   English   中英

Entity Framework Core GroupBy - 相關實體上的聚合函數

[英]Entity Framework Core GroupBy - aggregate functions on related entities

在 EF Core 中,使用 GroupBy 時,我無法獲取聚合函數來處理相關實體的字段。 這是一個例子來說明我的意思:

我正在嘗試運行以下查詢:

var list = db.Loans
   .GroupBy(x => x.Book.Isbn)
   .Select(
      x => new LoanQueryResult
      {
         Isbn = x.Key,
         AverageAge = x.Average(y => y.Member.Age)   // note here that I am navigating to a related entity
      }
   )
   .ToList();

因此,上述查詢的目標是,對於每本書 Isbn,我想要借閱它的會員的平均會員年齡。

Entity Framework Core 返回的錯誤如下:

The LINQ expression '(EntityShaperExpression: 
    EntityType: Loan
    ValueBufferExpression: 
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
).Member.Age' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

假設查詢需要從 Loans 表開始,我怎樣才能讓它工作?

這是我的 model(以防萬一):

public class Book
{
   public int Id { get; set; }
   public string Isbn { get; set; }
   public string Title { get; set; }

   public IList<Loan> Loans { get; set; }
}


public class Member
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string Surname { get; set; }
   public int Age { get; set; }

   public IList<Loan> Loans { get; set; }
}


public class Loan
{
   public int Id { get; set; }
   public int BookId { get; set; }
   public int MemberId { get; set; }
   public DateTime StartDate { get; set; }
   public DateTime EndDate { get; set; }

   public Book Book { get; set; }
   public Member Member { get; set; }
}

我會在 GroupBy 之前去規范化

var list = db.Loans
.Select(x => new
{
    x.Book.Isbn,
    x.Member.Age
}
.GroupBy(x => x.Isbn)
.Select(
  x => new LoanQueryResult
  {
      Isbn = x.Key,
      AverageAge = x.Average(y => y.Age)  
      }
)
.ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM