How to use linq group with count and return ToListAsync to front end

This is my code. I need to use linq group and count after return to front end by ToListAsync.
But I got a error like this pictureHow to use linq group with count and return ToListAsync to front end
How can I fix it?

    public async Task<List<Product>> GetDataChart()
    {
        var data = await dbMLIMPORT.Product
                    .GroupBy(g => new { g.CMID, g.SUB_CODE })
                    .Select(s => new
                    {
                        CMID = s.Key.CMID,
                        SUB_CODE = s.Key.SUB_CODE,
                        COUNT = s.Sum(x => x.PRODUCT_ID.Length > 0 ? 1 : 0)
                    }).ToListAsync();
        return data;
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to create a new class ProductInfo and return a list of ProductInfos instead of a list of Products. Currently, you are creating anonymous type inside the select query and returning the same which will produce this error.
I hope, it will solve your problem.

public class ProductInfo
{
    public string CMID {get; set;}
    public string SUB_CODE {get; set;}
    public int COUNT {get; set;}
}

public async Task<List<ProductInfo>> GetDataChart()
{
    var data = await dbMLIMPORT.Product
                .GroupBy(g => new { g.CMID, g.SUB_CODE })
                .Select(s => new ProductInfo
                {
                    CMID = s.Key.CMID,
                    SUB_CODE = s.Key.SUB_CODE,
                    COUNT = s.Sum(x => x.PRODUCT_ID.Length > 0 ? 1 : 0)
                }).ToListAsync();
    return data;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x