簡體   English   中英

Linq 與連接、組和總和不起作用

[英]Linq with join, group and sum not working

我是 Linq 和實體框架的新手,在我想要的代碼和結果下方。 在那里 LINQPad 工作得很好,但是當我把它帶到 net.core 我有這個錯誤:

.Sum(tot => tot.b.Price) 無法翻譯。 以可翻譯的形式重寫查詢,或通過插入對 AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync() 的調用顯式切換到客戶端評估

客戶
ID - 名稱
1 - 喬恩
2 - 亨利
3 - 最大

作品
ID - 價格 - ClientId
1 - 10 - 1
2 - 20 - 2
3 - 30 - 3
4 - 40 - 1
5 - 50 - 2

var result = await (from a in dbContext.Clients
                join b in dbContext.Works on a.Id equals b.ClientId
                        where b.Price != 0
                        group new {a, b} by new {a.Name, b.Price} into g
                        select new
                        {
                            Name = g.Key.Name,
                            Total = g.Sum(tot => tot.b.Price)//here is the problem!!!!!!!
                        }).ToListAsync();

結果:
約翰 50
亨利 70
最多 30 個

當您在 memory (即在 List 類的實例上)或在具有實體框架的數據庫上運行 Linq 查詢時,會有所不同。

在第一種情況下,代碼只是被執行,在第二種情況下,代碼在 SQL 查詢中被翻譯。 顯然,並非所有內容都是可翻譯的。

一種解決方案可能如下:

- 確保 class“客戶”參考了 class“作品”,即

 public class Clients {
       public string Id {get;set;}
       public string Name {get;set;}
       public IEnumerable<Works> Works {get;set;}
    }

-重寫您的查詢

 var result = await dbContext.Clients.Select(c => new {c.Name, c.Works.Sum(w => w.Price)}).ToListAsync();

我建議改進實體之間的導航,而不是使用過於復雜的查詢。

編輯:此解決方案不起作用,因為未指定分組依據。 您可能會發現這篇文章很有用: 如何在實體框架中對列求和

基本上,您需要以這種方式實現反向導航(即從 Works 到 Clients)

public class Works {
    public string Id {get;set;}
    public double Price {get;set;}
    public Clients Client {get;set;}
}

並使用以下查詢:

dbContext.Works.GroupBy(w => w.Client.Name).Select(g => new { Client = g.Key, Price = g.Sum(w => w.Price)}).ToListAsync()

暫無
暫無

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

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