How to get monthly order count by status in a Blazor Server application?

Cenk 1,051 Reputation points
2024-01-16T12:46:42.32+00:00

Hello, I am working on a Blazor Server application and need to find the number of monthly orders that are either completed or continue based on their status. I have a query that works for a specific year and status, but I need to refactor it to accept status and year as parameters. Here is the query I have so far:

Orders
.Where(x => x.OrderDateTime.Year == DateTime.Now.Year)
.GroupBy(x => new { Month = x.OrderDateTime.Month, Status = x.Status })
.Select(u => new 
        {
            Month = u.Key.Month,
			Status = u.Key.Status,
			Count = u.Count()
            
        })
		.OrderBy(u => u.Month)
Developer technologies | .NET | Entity Framework Core
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

Locked Question. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

2 answers

Sort by: Most helpful
  1. Wenbin Geng 746 Reputation points Microsoft External Staff
    2024-01-18T03:38:08.85+00:00

    Hi @Cenk, Welcome to Microsoft Q&A.

    I'm glad you were able to resolve your issue. Below I will explain some reasons so that you can have a deeper understanding of Blazor Server and EF Core.

    You are trying to use DateTime.Now.Year as part of a query criteria. This means you are trying to use the current year in C# in a LINQ query. However, Blazor Server applications execute on the server side, not the client, so DateTime.Now will return the server's current date and time, not the client's.

    So when you specify the year and status, you can get the query you want.

    Best Regards,

    Wenbin

    ---If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?

  2. Lorenzo Regalado 0 Reputation points
    2024-01-16T17:07:00.7933333+00:00

    Something like this ?

    var query = Orders
            .Where(x => x.OrderDateTime.Year == year && x.Status == status)
            .GroupBy(x => new { Month = x.OrderDateTime.Month })
            .Select(u => new
            {
                Month = u.Key.Month,
                Status = status,
                Count = u.Count()
            })
            .OrderBy(u => u.Month);
    

    Was this answer helpful?