Databases Reference
In-Depth Information
public override IQueryable GetQueryable(IQueryable query)
{
if (!string.IsNullOrEmpty(this.textBox.Text))
{
string filter = this.Column.Name + “ == @0”;
query = query.Where(filter, this.textBox.Text);
}
return query;
}
In this example, a
dynamic
version of the
Where
extension method is used. This method
takes a
string
that represents a logical condition and converts it into a lambda expression
LINQ needs to execute this query. Notice the use of the
MetaColumn.Name
property; it spec-
ifies the actual column name dynamically. With the City column, the filter string will be
“City==@0”,
and with ContactTitle, it will be
“ContactTitle==@0”
.
@0
is a placeholder for
the first parameter of the lambda expression, similar to parameters in dynamic SQL state-
ments. The actual parameter value,
TextBox.Text
, is passed as the second argument in the
call to the
Where
method.
NOTE
The
System.Linq.Dynamic
namespace, which provided the dynamic version of the
Where
extension method in this filter template, is
not
a part of the .NET Framework. It
is a C# sample project called
DynamicQuery
and can be found in the following folder of
the Visual Studio installation:
Microsoft Visual Studio 10.0
\Samples
\1033
\CSharpSamples.zip
\LinqSamples
\DynamicQuery
Before you can start using dynamic LINQ extensions in your project, you need to extract
the sample project from the following folder on your computer and add it to your solu-
tion. When compiled, the assembly can be used in both C# and Visual Basic projects.
The dynamic LINQ extensions make the task of creating queries dynamically almost as
easy as writing regular LINQ code. Compare the statically typed code shown here:
IQueryable<Customer> query = // …
query = query.Where(customer => customer.City == “London”);