Entity Framework Recipe: Grouping By Year And Month

3.94 (17 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: 30701

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

Sivu 19/10/2016 08:21
In response to Entity Framework Core TrackGraph For Disconnected Data
Oh that's very very very nice ! Thanks for the write up Mike, much appreciated for the taking the to...

Mark 12/10/2016 16:42
In response to ASP.NET Web Pages vNext or Razor Pages
Although "Web Pages" was removed from the roadmap, has it just been renamed to "Razor Pages"?...

Satyabrata 12/10/2016 09:20
In response to Entity Framework Core TrackGraph For Disconnected Data
Nice article. Please write more articles featuring ASP.Net web pages. Thank you...

Julian 26/09/2016 14:27
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Fantastic, many thanks Mike! Had got half way down this road before finding your article - saved...

Abolfazl Roshanzamir 14/09/2016 05:36
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Nice article. Thanke you so much ....

cyrus 02/09/2016 15:12
In response to ASP.NET Web Pages vNext or Razor Pages
I've got some news. As Damian stated in this link: https://github.com/aspnet/Mvc/issues/5208 “We...

Simon 01/09/2016 08:00
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Thanks Mike, nice post and exactly what I was looking for. Like you said, I think I'll opt to the...

dave 20/08/2016 14:57
In response to ASP.NET Web Pages vNext or Razor Pages
Do SimplemembershipProvider in viewpages is supported?...

Steven 18/08/2016 04:40
In response to Entity Framework Code First and Stored Procedures
Can you provide the directives (using statements) you're using for EF7 example?...

yousaid 17/08/2016 22:08
In response to ASP.NET Web Pages vNext or Razor Pages
Increasingly, learning a Microsoft tool is no longer worth the return on investment. Too many tools...