Entity Framework Recipe: Grouping By Year And Month

4.05 (19 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: 34302

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

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...