簡體   English   中英

EF Core 2.0 Group由其他屬性

[英]EF Core 2.0 Group By other properties

我有2張桌子:

USERS
UserId
Name
Scores (collection of table Scores)

SCORES
UserId
CategoryId
Points

我需要顯示所有用戶和他們的點的總和,但我還需要顯示用戶的名稱。 它可以通過CategoryId過濾或不過濾。

Context.Scores
.Where(p => p.CategoryId == categoryId) * OPTIONAL
.GroupBy(p => p.UserId)
.Select(p => new 
{
    UserId = p.Key,
    Points = p.Sum(s => s.Points),
    Name = p.Select(s => s.User.Name).FirstOrDefault()
}).OrderBy(p => p.Points).ToList();

問題是,當我添加

Name = p.Select(s => s.User.Name).FirstOrDefault()

這需要很長時間。 我不知道如何訪問不在GroupBy內部或是SUM的屬性。 這個例子非常簡單,因為我沒有Name,還有User表中的其他屬性。

我怎么解決這個問題?

這需要很長時間,因為查詢導致客戶端評估 請參閱客戶評估性能問題以及如何使用客戶端評估日志記錄來識別相關問題。

如果您真的使用EF Core 2.0,那么除了升級到包含改進的LINQ GroupBy轉換的 v2.1之外,您無能為力。 即使使用它,解決方案也不是直截了當 - 查詢仍然使用客戶端評估。 但是可以通過將GroupBy部分分成子查詢並將其連接到Users表來獲取所需的附加信息來重寫它。

像這樣的東西:

var scores = db.Scores.AsQueryable();
// Optional
// scores = scores.Where(p => p.CategoryId == categoryId);

var points = scores
     .GroupBy(s => s.UserId)
     .Select(g => new
     {
         UserId = g.Key,
         Points = g.Sum(s => s.Points),
     });

var result = db.Users
    .Join(points, u => u.UserId, p => p.UserId, (u, p) => new
    {
        u.UserId,
        u.Name,
        p.Points
    })
    .OrderBy(p => p.Points)
    .ToList();

這仍然會產生警告

LINQ表達式'orderby [p] .Points asc'無法翻譯,將在本地進行評估。

但至少查詢被翻譯並作為單個SQL執行:

SELECT [t].[UserId], [t].[Points], [u].[UserId] AS [UserId0], [u].[Name]
FROM [Users] AS [u]
INNER JOIN (
    SELECT [s].[UserId], SUM([s].[Points]) AS [Points]
    FROM [Scores] AS [s]
    GROUP BY [s].[UserId]
) AS [t] ON [u].[UserId] = [t].[UserId]

暫無
暫無

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

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