Introduction
Querying in memory objects presents a wide range of advantages over traditional database queries. Some of the most interesting advantages are listed below:
- Business developers need not get any knowledge about query languages like T-SQL or XPath.
- Promote decoupling between the data access and business layer.
- Decrease the numbers of open connections to database servers.
- Increase the performance by reducing the cost of IO operations.
- More domain specific, etc., etc.
In this article, I'll show you how to create criteria classes to perform queries against generics collections.
Background
Basic knowledge of .NET Generics.
Using the Code
For this article, I used AdventureWorks database, which you can download from here.
The sample project is pretty straightforward. It's just about performing queries like...
SELECT * FROM Employees WHERE FirstName LIKE 'Vilma'
...but instead of using SQL database, we'll use a generic collection of Employees as a data source.
The sample application consists of four libraries:
BusinessLayer (Business objects, criteria classes)
DataAccessLayer (Raw data access)
Repository (This library kept in memory all of the Employee instances within a generic collection)
WindowsFrontEnd (A simple Windows App to find customers based on a specific search criteria).
Now let's take a look at the main code blocks:
public abstract class BaseCriteria<T>
{
public abstract bool IsMatch(T entity);
}
A derived class from BaseCriteria should look like this:
public class FindByFirstNameLike : BaseCriteria<Employee>
{
_firstName;
public FindByFirstNameLike(string firstName)
{
_firstName = firstName.ToLower().Trim();
}
public override bool IsMatch(Employee entity)
{
return entity.FirstName.ToLower().StartsWith(_firstName) ||
string.IsNullOrEmpty(_firstName);
}
}
And finally we can see a criteria class in action:
private void ApplyFilters()
{
List<Employee> employees = Repository.Employees.GetEmployees();
List<Employee> searchResult = new List<Employee>();
searchResult = employees.FindAll(
new Employee.FindByFirstNameLike("Peter").IsMatch);
dgvResult.DataSource = searchResult;
dgvResult.Refresh();
}
In the download code, I included a Winform App that contains a sample of how to perform nested queries over the search results list.
I hope this article helps you to explore the power of .NET Generics.
If you have any doubts or suggestions about the code, please let me know.
History
- 9th January, 2009: Initial post