May 262013
 
Share...Tweet about this on Twitter2Share on Facebook2Share on Google+0Share on StumbleUpon0Share on LinkedIn3Flattr the authorPin on Pinterest0Share on Reddit0Share on TumblrDigg this

In the previous article Entity Framework Code First – Filtering And Sorting with paging (1) I have simply omitted to include the explanation of the “sorting” mechanism in the solution I’ve proposed. The intention was there but it was left out so I hope that this post will complete the whole story.

A short summary of the previous articles

For the new comers, this post is part of a trilogy, so to understand the whole picture you may follow:

For more details please check the article itself, but in summary what I am proposing is:

  1. A generic mechanism of retrieving data that enables paging, filtering and sorting when using EntityFramework
  2. The SearchQuery object that is responsible for holding the Filters, SortCriterias, Properties to be included in the result, Skip, Take
  3. A Search method, that is responsible for implementing what specified in the SearchQuery
  4. PagedListResult that holds the returning data
Please consider downloading a fully working example of the code covered in this post:
EntityFramework_SearchQuery_v2
This version contains a bug fix related to Sorting.

Searching

At the basis of the search is the ISortCriteria interface that declares the Direction that is just saying if the ordering is DESC or ASC, and the ApplyOrdering method that is responsible for the sorting itself, all the rest is left to the implementor of the interface itself.

public interface ISortCriteria<T>
{
  SortDirection Direction { get; set; }
     
  IOrderedQueryable<T> ApplyOrdering(IQueryable<T> query, Boolean useThenBy);
}

After the search is performed, the ApplyOrdering method will be called, so that is in reality the “heart” of the search itself.

ISortCriteria implementations

I am proposing two different Sorting Mechanism implementations, the outcome is the same, but it’s usage simply differs slightly.

FieldSortCriteria

FieldSortCriteria offers the sorting by specifying the Name and the SortDirection in a non-strongly typed way. While this could be pretty much error prone as there is no type checking at compile time, it offers the possibility to directly specify the name of the Property (as a string) on which we want to have the sorting mechanism.
FieldSortCriteria could be used to simplify the code especially if used in the ASP.NET MVC controllers where we want to enable dynamic sorting, where the name of the sorting field is passed dynamically.

For the implementation of the FieldSortCriteria class please download the source code directly.

The code below is one example of how to use the FieldSortCriteria class. SearchQuery enables more than one sort criteria at a time, so sorting by several fields is possible.

private static void FieldSortCriteriaTest()
{
  var productRepository = new Repository<Product>();

  var q = new SearchQuery<Product>();
 
  q.AddSortCriteria(
      new FieldSortCriteria<Product>("Name", SortDirection.Ascending));

  q.AddSortCriteria(
      new FieldSortCriteria<Product>("IsActive", SortDirection.Ascending));

  var result = productRepository.Search(q);

  foreach (var product in result.Entities)
  {
       Console.WriteLine("Name=" + product.Name + ";" +
                         "IsActive=" + product.IsActive);
  }    
}

Output of the above is as follows:

--------------FieldSortCriteria------------------------
Name=Book Title 1; IsActive=True
Name=Book Title 2; IsActive=False
Name=Bred; IsActive=True
Name=unspec product; IsActive=True

ExpressionSortCriteria

ExpressionSortCriteria offers the same sort of sorting mechanism but with the only difference that this supports static typing, meaning that the possible errors will be found directly at a compile time.

The method below, produces the same output as the FieldSortCriteria example.

private static void ExpressionSortCriteriaTest()
{

    var productRepository = new Repository<Product>();

    var q = new SearchQuery<Product>();

    q.AddSortCriteria(new ExpressionSortCriteria<Product, string>
                                  (x => x.Name,
                                   SortDirection.Ascending));

    q.AddSortCriteria(new ExpressionSortCriteria<Product, bool>
                                  (x => x.IsActive,
                                   SortDirection.Ascending));

    var result = productRepository.Search(q);

    foreach (var product in result.Entities)
    {
     Console.WriteLine("Name=" + product.Name + ";" +
                                  "IsActive=" + product.IsActive);
    }
}

The difference between the two sorting mechanism

As already stated, the difference is pretty much in how do we want to call the method, as the produced result is literally the same.

If you have a static query that doesn’t change overtime I would use the ExpressionSortCriteria, as in case of code refactoring, any change would be picked up at the compile time.

In case of dynamic queries where you don’t know what is the ordering to be applied (searching for data, ordering a grid, etc..) FieldSortCriteria is probably more “handy” as it is easier to code, but the same thing can be achieved with ExpressionSortCriteria.

A small example of the “verbosity of the ExpressionSortCriteria:
Immagine to have a generic method that accepts a fieldName and a direction for sorting, so you will be forced to use if statements, or switch in order to return the correct sorting criteria.

public static ISortCriteria<Product> SortBy(string field, string direction)
{
    if (field == "Name")
    {
        SortDirection sortDirection = (direction == "ASC")
                                            ? SortDirection.Ascending
                                            : SortDirection.Descending;
                
        return new ExpressionSortCriteria<Product, string>
                                            (x => x.Name, sortDirection);
    }
    return null;
}

Final thoughts

I hope that with this third article, the circle is closed, as all of the elements of the solution are presented. I am personally using this mechanism in one of the projects where I am working, and the baseline for the code is more or less the same. This said, the code is far from being perfect and it’s a mix of concepts that I put together by reading various sources on the web, that at this point of time got lost or forgotten, so a big thanks to other folks with great ideas!
Please let me know if you have doubts or if you think that there is something that could be improved as I will include this in the solution with a great pleasure.

Share...Tweet about this on Twitter2Share on Facebook2Share on Google+0Share on StumbleUpon0Share on LinkedIn3Flattr the authorPin on Pinterest0Share on Reddit0Share on TumblrDigg this

My name is Zoran Maksimovic a Software Developer and Solution Architect. I'm interested in Software Development, Object-Oriented Design and Software Architecture all this especially bound to the Microsoft.NET platform. Feel free to contact me or know more in the about section

  One Response to “Entity Framework Code First – Filtering And Sorting with paging (2)”

  1. Isn’t this going to be addressed in EF7?

Leave a Reply

mccaine@mailxu.com sumidahoa@mailxu.com