Hi,
In this article I’ll shows a pretty useful way to build simple LinqToSql Queries with reusable IQueryable<T> Extension Methods.
Assuming a LinqToSql DataContext which contains a single Class named “User”
Now we want to Query a User by it’s Email Address.
Using Standard Linq Query we do the following in our UserController Class :
public User GetByEmail(String email)
{
return Context.Users.Where(p => p.Email == email).SingleOrDefault();
}
This works fine but we can make this Where clause Reusable for further usages.
So we create a Extension Methods Class called UserExtensions :
public static class UserExtensions
{
public static IQueryable<User> WithEmail(this IQueryable<User> q, String email)
{
return q.Where(p => p.Email == email);
}
}
We can now modify our GetByEmail method and use our Extension method :
public User GetByEmail(String email)
{
return Context.Users.WithEmail(email).SingleOrDefault();
}
This is now clear and Reusable !
Some other Examples :
public Boolean IsValidUser(String email, String password)
{
var q = Context.Users.WithEmail(email).WithPassword(password);
return q.SingleOrDefault() != null;
}
public Boolean UserExists(String email)
{
return Context.Users.WithEmail(email).SingleOrDefault() != null;
}
So here is how to take Advantage of the IQueryable Interface with Extension Methods.
Hope this help’s!
Views(3112)

