Search code examples
c#.netentity-framework-corelinq-to-entities

How can I run these 2 calls to sum values as one call in EF Core?


Is there a way to make these 2 calls 1? Both are from the same table, just different values.

var grossAmount = await _dbContext.StripeTransfers
  .Where(p => p.StripePayoutId == payout.StripePayoutId)
  .Select(p => p.GrossAmount)
.SumAsync();

var totalTokens = await _dbContext.StripeTransfers
  .Where(p => p.StripePayoutId == payout.StripePayoutId)
  .Select(p => p.Tokens)
.SumAsync();

Solution

  • As recommended in a comment making a SQL statement might be more efficient here, but if you are wanting to stay in realm of EF and LINQ you can do something like this:

    var result = await _dbContext.StripeTransfers
        .Where(p => p.StripePayoutId == payout.StripePayoutId)
        .GroupBy(p => p.StripePayoutId)
        .Select(g => new
        {
            GrossAmountSum = g.Sum(p => p.GrossAmount),
            TokensSum = g.Sum(p => p.Tokens)
        })
        .FirstOrDefaultAsync();
    
    // Here you can do whatever you want with variables.
    var grossAmount = result?.GrossAmountSum ?? 0;
    var totalTokens = result?.TokensSum ?? 0;