簡體   English   中英

如何發送 Func 類型的變量<t,decimal>使用 ef core 從 IQueryable 求和</t,decimal>

[英]how to send variable of type Func<T,decimal> to sum from IQueryable using ef core

我需要在 function 參數中發送一個 lamda,但是當我這樣做時,我錯誤地說

“System.Func 2[KokazGoodsTransfer.Models.Receipt,System.Decimal]' cannot be used for parameter of type 'System.Linq.Expressions.Expression 1[System.Func 2[KokazGoodsTransfer.Models.Receipt,System.Decimal]]' of method 'System.Decimal Sum[Receipt](System.Linq.IQueryable 1[KokazGoodsTransfer.Models.Receipt], System.Linq.Expressions.Expression 1[System.Func [TransferSystem.Func.Receiptaz, GoodsSystem.Func.Receipt] .Decimal]])'(參數'arg1')'

代碼示例

var sum = await context.Receipts.GroupBy(c => c.ClientId).Select(c => new { c.Key, Sum = c.Sum(c=>c.Amount) }).ToListAsync();

它工作正常

但是當我嘗試這個時,我看到了錯誤

Func<Receipt, Decimal> func = c => c.Amount;
var sum = await context.Receipts.GroupBy(c => c.ClientId).Select(c => new { c.Key, Sum = c.Sum(func) }).ToListAsync();

謝謝你

EF 通常需要一個表達式樹才能將代碼轉換為實際的 SQL 查詢。

你可以嘗試這樣的事情(雖然沒有經過測試,但在某些情況下,據我所知,這些技巧有效):

Expression<Func<Receipt, Decimal>> func = c => c.Amount;
var sum = await context.Receipts
    .GroupBy(c => c.ClientId)
    .Select(c => new { c.Key, Sum = c.AsQueryable().Sum(func) })
    .ToListAsync();

否則,您可能需要手動構建 select 語句表達式(這並不容易),或者查看像LINQKit這樣的第三方庫,它允許使用Func一些魔法。 沿着這條線的東西:

Expression<Func<Receipt, Decimal>> func = c => c.Amount;
var sum = await context.Receipts
    .AsExpandable() // or WithExpressionExpanding on the context DI set up
    .GroupBy(c => c.ClientId)
    .Select(c => new { c.Key, Sum = c.Sum(func.Compile()) })
    .ToListAsync();

您必須使用不是Func而是Expression<Func<Receipt, Decimal>> 但如果沒有第三方擴展,它也將無法翻譯。 我建議使用LINQKit 它只需要配置DbContextOptions

builder
    .UseSqlServer(connectionString) // or any other provider
    .WithExpressionExpanding();     // enabling LINQKit extension

然后您的查詢將按以下方式工作:

Expression<Func<Receipt, Decimal>> func = c => c.Amount;

var sum = await context.Receipts.GroupBy(c => c.ClientId)
  .Select(c => new { c.Key, Sum = c.Sum(x => func.Invoke(x)) })
  .ToListAsync();

暫無
暫無

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

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