实体框架核心GroupBy-聚合相关实体上的功能

时间:2020-06-10 16:12:14

标签: c# entity-framework linq entity-framework-core

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

因此,上述查询的目标是,对于每本《伊斯本》,我想要借书的会员的平均会员年龄。

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.

假设查询需要从“贷款”表中开始,该如何工作?

这是我的模型(以防万一):

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

1 个答案:

答案 0 :(得分:1)

我会在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();