[英]Entity Framework Core GroupBy - aggregate functions on related entities
In EF Core, when using GroupBy I cannot get aggregate functions to work on fields from related entities.在 EF Core 中,使用 GroupBy 时,我无法获取聚合函数来处理相关实体的字段。 Here is an example to illustrate what I mean:
这是一个例子来说明我的意思:
And I am trying to run the following query:我正在尝试运行以下查询:
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();
So the objective in the above query is, for each Book Isbn, I want the average member age of the Members who have borrowed it.因此,上述查询的目标是,对于每本书 Isbn,我想要借阅它的会员的平均会员年龄。
The error that Entity Framework Core returns is as follows: 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.
How can I get this working, on the assumption that the query needs to start out from the Loans table?假设查询需要从 Loans 表开始,我怎样才能让它工作?
Here is my model (in case it helps):这是我的 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; }
}
I would denormalize before the GroupBy我会在 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.