Entity Framework Recipe: Grouping By Year And Month

4.1 (20 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.

 

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

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

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....