Sunday, January 15, 2012

On-the-fly building on where clauses of query statements to
fire against a data store is a common problem in most of the applications. Linq
is a concept of querying data a first class programming concept in .NET, and
enables you to efficiently express queries in your programming language of
choice. Linq allows you to write type-safe queries, most of the times you need
to construct queries on the fly based on some filter conditions.

The Dynamic query library provided by Microsoft helps you to
construct linq queries by passing a string value for where condition or an
expression that can be evaluated at runtime. In this post we'll see how to
construct expressions for the where clause dynamically using a combination of
builder and specification pattern.

Creating a class for filter options

publicclassUsersFilterOption

{

publicstring Name { get; set; }

publicstring Country
{ get; set; }

publicstring Role { get; set; }

publicstring Email {
get; set; }

publicstring
Telephone { get; set;
}

}

The condition builder class is used to add expressions as specifications to the Specification based on the filter options.

publicclassUserWhereConditionExpressionBuilder

{

privatereadonlyUsersFilterOption _filterOptions;

privateSpecification<User> _result = newTrueSpecification<User>();

public UserWhereConditionExpressionBuilder(UsersFilterOption usersFilterOptions)