简体   繁体   中英

Convert Sql to linq with groupby

I have view on which I use this request

Select Spendband, SUM(SpendCurrencyJob), SUM(SpendDocumentCount)
From analysis.vwJobSupplierMetrics
Where JobId = '500E0DD1-E3D3-4887-95EF-01D3C9EA8FD0'
Group by SpendBand

And it's running sucessfully

and get me this data

在此处输入图像描述

How I need to write it using linq to get same data?

I tried like this

    var data = await _dbContext.VwJobSupplierMetrics.Where(x => x.JobId == jobId)
            .GroupBy(x => x.SpendBand)
            .Select(x => new HumpChartDto() {SpendBand = x.SpendBand}).ToListAsync();

But on new HumpChartDto() {SpendBand = x.SpendBand} I got Cannot resolve symbol 'SpendBand

How I can solve this?

First, after grouping on SpendBand , you need to access it via Key property. Second, to compute Sum, you can use Sum method.

var data = await _dbContext.VwJobSupplierMetrics.Where(x => x.JobId == jobId)
    .GroupBy(x => x.SpendBand)
    .Select(x => new HumpChartDto() 
    {
        SpendBand = x.Key,
        SumOfSpendCurrencyJob = x.Sum(s => s.SpendCurrencyJob),
        SumOfSpendDocumentCount= x.Sum(s => s.SpendDocumentCount),
    })
    .ToListAsync();

Note - change the property name accordingly for name I've used for SumOfSpendCurrencyJob and SumOfSpendDocumentCount as don't know the definition of HumpChartDto class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM