Entity Framework Recipe: Grouping By Year And Month

4 (18 votes)

This is the latest in a series of "EF Recipes" - short articles that show through practical examples how to achieve common tasks with Entity framework and ASP.NET MVC. This particular example looks at grouping data by year and month in MVC 5 with Entity Framework 6. The article is prompted by an email I got from a reader who asked how I generate the "Archives" feature in the right hand panel on each page on this site.

This example will centre on displaying the orders in the Northwind database grouped by year and month to illustrate that the approach can be applied to any data items that have a date. Items will have the month name and total for the month listed by year. There are three aspects to the solution to this problem: the ViewModel; the data query; and the actual display of the data. The following code shows the ViewModel:

using System.Globalization;

public class ArchiveEntry
{
    public int Year { get; set; }
    public int Month { get; set; }
    public string MonthName
    {
        get
        {
            return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(this.Month);
        }
    }
    public int Total { get; set; }
}

The class includes three auto-implemented properties and one that returns a month name based on the integer value of the Month property. The MonthName will be used when the data is displayed.

The data is retrieved in the Index action of the Home controller:

public ActionResult Index()
{
    var context = new EFRecipeContext();
    var model = context.Orders
        .GroupBy(o => new 
        { 
            Month = o.OrderDate.Month, 
            Year = o.OrderDate.Year 
        })
        .Select(g => new ArchiveEntry
        {
            Month = g.Key.Month,
            Year = g.Key.Year,
            Total = g.Count()
        })
        .OrderByDescending(a => a.Year)
        .ThenByDescending(a => a.Month)
        .ToList();

    return View(model);
}

The pure SQL version of the query might look like this:

SELECT 
    DATEPART (month, OrderDate), 
    DATEPART (year, OrderDate), 
    COUNT(DATEPART (month, OrderDate)) 
FROM 
    Orders 
GROUP BY 
    DATEPART (month, OrderDate), 
    DATEPART (year, OrderDate)
ORDER BY 
    DATEPART (year, OrderDate) DESC,
    DATEPART (month, OrderDate) DESC

The EF generated SQL is a little more verbose but performs pretty much the same as hand written SQL.

In the LINQ query, the DATEPART function translates to referencing the Month and Year properties of the OrderDate, which is a DateTime type. You want to group the data by mutiple value (the year and month). This is done in the LINQ version of the query by generating an anonymous type as the key for each group:

.GroupBy(o => new 
{ 
    Month = o.OrderDate.Month, 
    Year = o.OrderDate.Year 
})

Then the data is projected into a List of ArchiveEntry objects, ordered by year descending, then by month, and passed to the View where it is displayed:

EF6 Recipe Group by year month

The code for displaying the data is as follows:

@foreach (var group in Model.GroupBy(m => m.Year))
{
    <ul>
        <li>
            @group.Key
            <ul>
                @foreach (var item in group)
                {
                    <li>
                    @Html.RouteLink(
                        string.Format("{0} ({1})",item.MonthName, item.Total),
                        "",
                        new
                        {
                            controller = "Home",
                            action = "Archive",
                            year = item.Year,
                            month = item.Month
                        })
                    </li>
                }
            </ul>

        </li>
    </ul>
}

The data is grouped by Year and nested lists are used to display the data for each year. I have generated links in this example to show how that is done - using the ArchiveEntry object's MonthName property. The Year and Month values are added to the generated url as query string values.

This recipe has shown you how to use Entity Framework to group data by multiple parts of a date, and how to translate the T-SQL DATEPART function to a LINQ query.

 

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 32638

3 Comments

- Satyabrata

Nice article. Learned a lot. Thanks for sharing.

- Jamal

Very useful! Thank you very much!

- Ahsan

Can you show how we can group by this behaviour:

GROUP BY
DATEPART (year, OrderDate)
DATEPART (week, OrderDate),
}

Recent Comments

Cyrus 26/05/2017 06:00
In response to Razor Pages - The Elevator Pitch
There are some concern about razor pages performance. Is it faster or slower than MVC? would you a a...

Cyrus 26/05/2017 05:44
In response to Razor Pages - Understanding Handler Methods
well done, thank you....

Satyabrata Mohapatra 23/05/2017 11:41
In response to Razor Pages - Understanding Handler Methods
Nice and easy !! Great post....

Cyrus 16/05/2017 19:55
In response to Razor Pages - Getting Started With The Preview
There is something wrong related to microsoft.dotnetcore.mvc.taghelpers! if you remove it from page...

Cyrus 16/05/2017 10:18
In response to Razor Pages - Getting Started With The Preview
well done mike, it was very useful, I really appreciate that....

Satyabrata Mohapatra 16/05/2017 07:21
In response to Razor Pages - Getting Started With The Preview
Finally!!!! web pages in asp.net core!!! Super excited !!!! Thank u sir for sharing.....Awaiting on...

Daniele 14/03/2017 10:24
In response to Working With Zip Files In ASP.NET MVC
is it possible give to the user a progress bar of the zipping process? Thanks in advance. ...

Suraj 13/03/2017 22:20
In response to Working With Zip Files In ASP.NET MVC
Very nice article. Thanks....

Satyabrata Mohapatra 19/02/2017 03:01
In response to Free SSL Certificates On IIS With LetsEncrypt
Thanks for sharing. Learned a lot !!...

Gfw 03/02/2017 09:48
In response to Free SSL Certificates On IIS With LetsEncrypt
I have used WinSimple for about the last 9 months - works great. One thing that you want to make of...