I’ve been doing a fair amount of work with Entity Framework recently. There are some things about EF that make me want to throw it out the window, but this post is about something that I really like, the ability to eliminate redundant code from my BLL and DLL and create a fluent interface for composing queries.
The problem we want to solve
So here’s a typical scenario. I have a blog aggregator application that I’m building. I use Entity Framework to create a BlogPost entity and it’s data mappings. Great, now I’m ready to create a BlogRepository class that will contain all of my queries for getting Blog posts. So I write the first data access method and it looks something like this.
public List<BlogPost> BlogPostSetByWeek_GetPage(int pageIndex, int pageSize, DateTime startDate)
{
startDate = ToSunday(startDate);
DateTime startUtc = startDate.Date;
DateTime endUtc = startDate.AddDays(7).Date;
int skipCount = pageSize * pageIndex;
var query = from p in Context.BlogPostSet.Include("Categories")
where p.PostedUtc > startUtc & p.PostedUtc < endUtc
orderby p.PostedUtc descending
select p;
List<BlogPost> postSet = query.Skip(skipCount).Take(pageSize).ToList<BlogPost>();
return postSet;
}
The above method takes a startDate and some paging parameters and then returns the specified page of results in the shape of a generic list of BlogPost entities. How easy was that!!
Now for the next step. I need a query that’s exactly like the query above but this time I want the entire list of results instead of just a page. And after that I need another query that sorts the BlogPosts by Category instead of by PostedUtc, and then I need another that sorts by the BlogName, and on and on and on. So how do I handle this?? I could just create a completely new EF query for each one of these. Or maybe I could use EntitySQL instead of Linq to Entities and then I would be able to use a bunch of conditional blocks to create the EntitySQL text that I need….. Neither of those solutions really appeals to me. First, I don’t like the idea of rewriting the same query over and over with minor differences in criteria or sort order. That just seems inefficient. Second I don’t really want to use EntitySQL because I like the strong typing that I get with Linq to Entities, plus I would need a lot of conditionals to handle all of the possible query combinations and that sounds like a mess.
The Solution
So I was thinking about how much I hate duplicating the same query code over and over when I realized something. Microsoft has made the query an object. I didn’t really appreciate the significance of that before. The query is no longer just text, it is now an object, an ObjectQuery<> object to be precise. The cool part is that if I write methods that take an ObjectQuery as their parameter and then return an ObjectQuery for their return value, I can chain them together and use them to compose queries.
How could this work? I looked at the queries in my BLL and found that each of them consists of 3 major components:
Looking at this break down, I realized that I could have a Filter Method that creates an ObjectQuery that gets the data I’m looking for, then I could pass that ObjectQuery to a Sort Method that applies a sort then returns the modified ObjectQuery, then I could pass that to a Projection Method that applies paging, shapes the data, and executes the ObjectQuery.
So, when all this is said and done I should be able to compose Entity framework queries by combining a Filter Method, a Sort Method, and a Projection Method. The end result should be data access code that looks like this:
List<BlogPost> postSet = GetBlogPostSet().SortBy(“Date”).GetPage(pageIndex, pageSize);
List<BlogPost> postSet = GetBlogPostSet().SortBy(“ID”).GetPage(pageIndex, pageSize);
List<BlogPost> postSet = GetBlogPostSet().SortBy(“ID”).GetAll();
Building an Example
So, I coded it up and it works pretty well. The first step is creating a Filter Method. This method takes search criteria as parameters and returns an ObjectQuery. Below is my filter method for getting the BlogPost entities for a given week.
// GetBlogPostSetForWeek
private ObjectQuery<BlogPost> GetBlogPostSetForWeek(DateTime startDate)
{
startDate = ToSunday(startDate);
DateTime startUtc = startDate.Date;
DateTime endUtc = startDate.AddDays(7).Date;
var query = from p in Context.BlogPostSet.Include("Categories")
where p.PostedUtc > startUtc & p.PostedUtc < endUtc
select p;
return (ObjectQuery<BlogPost>)query;
}
Now I need to create my Sort Method. This method will take the results of my Filter Method as a parameter, along with an enum that tells the method what sort to apply. Note that I’m using strongly typed object queries of type ObjectQuery<BlogPost>. The strong typing serves two purposes. First it lets my Sort Method know that I’m dealing with BlogPost entities which tells me what fields are available to sort by. Second, the stong typing provides a distinct method signature so I can have multiple methods called SortBy which all handle ObjectQueries that return different types of entities. I can have a SortBy( ObjectQuery<BlogPost>), SortBy(ObjectQuery<Person>), etc.
One other thing. I want to chain these methods together, fluent interface style. For that reason I’m implementing both SortBy and my GetPage as extension methods. Here’s the code for the SortBy method.
// SortBy
internal static ObjectQuery<BlogPost> SortBy( this ObjectQuery<BlogPost> query, Enums.BlogPostSortOption sortOption)
{
switch (sortOption)
{
case Enums.BlogPostSortOption.ByDate:
return (ObjectQuery<BlogPost>)query.OrderByDescending(p => p.PostedUtc);
case Enums.BlogPostSortOption.BySite:
return (ObjectQuery<BlogPost>)query.OrderBy(p => p.BlogProfile.BlogName);
case Enums.BlogPostSortOption.ByVote:
return query;
default:
return (ObjectQuery<BlogPost>)query.OrderByDescending(p => p.PostedUtc);
}
}
Lastly we need to create a Projection Method. Below is the GetPage method. It takes the ObjectQuery<BlogPost> from the SortBy method, applies paging logic to it, executes the query, then returns the results as a List<BlogPost>.
// GetPage
internal static List<BlogPost> GetPage(this ObjectQuery<BlogPost> query, int pageIndex, int pageSize)
{
int skipCount = pageSize * pageIndex;
return query.Skip(skipCount).Take(pageSize).ToList<BlogPost>();
}
So that’s it. I now have all the pieces needed to create my data access methods without duplicating query logic over and over. If I want all blog posts ordered by date, I can use the code:
Enums.BlogPostSortOption sort = Enums.BlogPostSortOption.ByDate;
return GetBlogPostSetForWeek(startDate).SortBy(sort).GetPage(pageIndex, pageSize);
To sort those same results by BlogName I can use the code:
Enums.BlogPostSortOption sort = Enums.BlogPostSortOption.BySite;
return GetBlogPostSetForWeek(startDate).SortBy(sort).GetPage(pageIndex, pageSize);
If I want to get BlogPosts by category instead of by week, I just write a new filter method named GetBlogPostSetForCategory and it plugs right in:
return GetBlogPostSetForCategory(category).SortBy(sort).GetPage(pageIndex, pageSize);
Conclusion
So that's it. This technique has significantly reduced the amount of data access code in my Repository classes and the time that it takes to write it. I also like the fact that I’m not writing the same paging and sorting code over and over in different queries. If you see any advantages or disadvantages to the technique, please leave a comment and let me know what you think. Also, if you’re aware of anyone else using a similar method, please send me a link at rlacovara@gmail.com, I would like to check it out.
This is very interesting. Thanks.
ReplyDeleteJust as an FYI, if you have much more complex needs for dynamically composing queries, you should consider using Entity SQL. I have done some very cool stuff by combining .NET Generics, Entity SQL and EF's MetadataWorkspace.
ReplyDeleteJulie, thank you for the comment. I read your book the week it came out, I recommend it for anyone getting into EF. If you have a blog post on the techniques you mentioned please post a link. I would love to check it out.
ReplyDeleteRudy, I never saw the reply to my comment until just now. BUt the reason I did was because I'm reading some of your posts because I like the perpsective you come from.
ReplyDeleteI recently did a webcast for O'REily called EF Tips & Tricks. If you download the code for that from my book's site (learnentityframework.com/downloads ...bottom of page) you'll find a GetReferenceList method in the ESQLTips.cs file. It shows the basic concept of using ESQL to write resuable queries. hth
julie