.NET 4.5 Extension Methods on IQueryable

Exclusive offer: get 50% off this eBook here
Instant .NET 4.5 Extension Methods How-to [Instant]

Instant .NET 4.5 Extension Methods How-to [Instant] — Save 50%

Utilize and harness the power of extension methods in your .NET applications with this book and ebook

$19.99    $10.00
by Shawn R. McLean | May 2013 | .NET Enterprise Articles

In this article by Shawn R. McLean, author of Instant .NET 4.5 Extension Methods How-to , we learn about the extension methods on IQueryable. IQueryable is used to operate mainly on databases. IQueryable<T>are an extension from IEnumerable<T>, hence, we can call all extensions and methods of IEnumerable<T>. A query using IQueryable can be built up on over time, before it hits the database. The query is executed once you execute an eager function such as ToList(), looping the data or attempting to use the values. IQueryable is used by providers such as LINQ to entities or LINQ to SQL.

(For more resources related to this topic, see here.)

Getting ready

Refer to the IQueryableExtensions.cs file in the ExtensionMethods.Libraryproject for the extension methods. The models are located in Models/PagedList.cs and Models/IPagedList.cs. These methods are used in the IQueryableExtensionTests.cs file in the ExtensionMethods.Tests project.

How to do it...

The following code snippet shows a general use of extension methods on IQueryables:

public static User ByUserId(this IQueryable<User> query, int userId) { return query.First(u => u.UserId == userId); }

The following code snippet is a paged list class for pagination of data:

public class PagedList<T> : List<T>, IPagedList { public PagedList(IQueryable<T> source, int index, int pageSize) { this.TotalCount = source.Count(); this.PageSize = pageSize; this.PageIndex = index; this.AddRange(source.Skip(index * pageSize).Take(pageSize). ToList()); } public PagedList(List<T> source, int index, int pageSize) { this.TotalCount = source.Count(); this.PageSize = pageSize; this.PageIndex = index; this.AddRange(source.Skip(index * pageSize).Take(pageSize). ToList()); } public int TotalCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public bool IsPreviousPage { get { return (PageIndex > 0); } } public bool IsNextPage { get { return (PageIndex * PageSize) <=TotalCount; } } }

The following code snippet is the extension method that executes and converts the query to the PagedList object:

public static PagedList<T> ToPagedList<T>(this IQueryable<T> source, int index, int pageSize) { return new PagedList<T>(source, index, pageSize); }

The following code snippet shows how we use these extension methods:

[TestMethod] public void UserByIdReturnsCorrectUser() { var query = new List<User> { new User {UserId = 1}, new User {UserId = 2} }.AsQueryable(); var user = query.ByUserId(1); Assert.AreEqual(1, user.UserId); } [TestMethod] public void PagedList_Contains_Correct_Number_Of_Elements() { var query = new List<int>{1,2,3,4,5,6,7,8,9,10}.AsQueryable(); var pagedList = query.ToPagedList(0, 5); Assert.AreEqual(5, pagedList.Count); Assert.AreEqual(10, pagedList.TotalCount); }

How it works...

The first code snippet ByUserId is the most commonly used type of extension method for IQueryable types. An alternative to this method is to use the repository pattern and add a method of getting a user by the Id. But sometimes, we will expose the query to lower levels of the app such as the service layer where we might need to use this feature at multiple places, hence refactoring that logic into an extension method makes perfect sense.

This extension method evaluates and executes the query immediately due to requesting a single value using the First() method:

query.First(u => u.UserId == userId);

The second code snippet gives us a PagedList model which becomes a valuable class when working with grids or pagination. The constructor accepts an IQueryable or IList and converts that data into a paged list. Take note of the line in which we evaluate the source by calling ToList(). This line executes the query on the provider:

this.AddRange(source.Skip(index * pageSize).Take(pageSize).ToList());

In the code snippets using these extension methods, we have created a list and cast it to an IQueryable type. This is purely for the purpose of demonstration. In a real application, the query would be coming from a LINQ to SQL or entities context, which is in charge of executing the query against a database.

We need to be careful of how extension methods on IQueryable are written. A poorly written query will result in unexpected behavior, such as premature query execution. If the extension method is simply building up the query (using method chaining), ensure that the query is not evaluated inside the method. If the query is evaluated and executed before the method finishes, any other use of the query outside of the extension method will result in operating on the data in memory.

Summary

In this article, you have learned a few tricks and caveats when using extending IQueryable.

Resources for Article :


Further resources on this subject:


Instant .NET 4.5 Extension Methods How-to [Instant] Utilize and harness the power of extension methods in your .NET applications with this book and ebook
Published: April 2013
eBook Price: $19.99
See more
Select your format and quantity:

About the Author :


Shawn R. McLean

Shawn R. McLean is passionate about architecting and developing scalable mobile and web applications based on the Microsoft .NET platform using ASP.NET MVC, ASP.NET WebAPI, and C#, along with using open source frameworks. He is an advocate of software and builds engineering methodologies for a streamlined development process. Besides his love for software engineering, architecture, and design, he also focuses on artificial intelligence and has interest in researching on computer vision and machine learning.

In 2008, he was a gold medalist in the web design category of World Skills Jamaica and a Best of Nation awardee for World Skills International, 2009. In 2009, he was also a finalist for the Microsoft Imagine Cup software design competition in Egypt, where he was the team lead of four, successfully clearing three rounds in a competition of more than 15 teams from around the Central Caribbean. In 2010, he led his team to first place of the Imagine Cup Interoperability award in Poland. He is also the recipient of Jamaica’s Prime Minister’s Youth Awards, Governor General’s iBelieve award, the Gleaner award, and the Chamber of Commerce award for outstanding innovation in the field of technology and science.

He is currently employed by the University Information System Services division of Northern Caribbean University, where he is part of a software engineering team that builds student and learning management systems for universities and high schools. He is also the co-founder of Xormis, a start-up software engineering company that makes in-house mobile and web-based applications for commercial use.

Books From Packt


 .Net Framework 4.5 Expert Programming Cookbook
.Net Framework 4.5 Expert Programming Cookbook

 Microsoft .Net Framework 4.5 Quickstart Cookbook
Microsoft .Net Framework 4.5 Quickstart Cookbook

Visual Studio 2012 and .NET 4.5 Expert Development Cookbook
Visual Studio 2012 and .NET 4.5 Expert Development Cookbook

 NHibernate 3 Beginner's Guide
NHibernate 3 Beginner's Guide

 Entity Framework 4.1: Expert’s Cookbook
Entity Framework 4.1: Expert’s Cookbook

ASP.NET 4 Social Networking
ASP.NET 4 Social Networking

 LINQ Quickly
LINQ Quickly

 Entity Framework Tutorial
Entity Framework Tutorial


Your rating: None Average: 1.6 (5 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
7
x
U
i
b
G
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software