Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading