Entity Framework Recipe: Grouping By Year And Month

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...