Databases Reference
In-Depth Information
gridView.DataSource = customers.ToArray();
gridView.DataBind();
}
With the help of strongly typed classes, LINQ takes advantage of the compiler and elimi-
nates the simple, but all too common, errors caused by misspelled table and column
names in SQL queries. However, its biggest advantage is not the convenience of having
the compiler check your code for typos. LINQ queries are first compiled into expression
trees before they are translated into dynamic, parameterized SQL statements and sent to
the database server for execution.
Although having the query compiled into an expression might seem like overhead at first,
it offers two important advantages. On one hand, it protects the application against SQL
injection attacks. Any malicious search string provided by the user, such as
“'; drop
table Customers;'”
are passed to the database server as a
parameter value
and not as part
of the query itself. On the other hand, LINQ expressions can be manipulated to customize
the query. The following code snippet shows how you could implement filtering logic for
this sample Customer search page using LINQ:
using (NorthwindEntities context = new NorthwindEntities())
{
IQueryable<Customer> customers = context.Customers;
if (this.cityFilter.Text.Length > 0)
customers = customers.Where(c => c.City == this.cityFilter.Text);
if (this.titleFilter.Text.Length > 0)
customers = customers.Where(c=>c.ContactTitle==this.titleFilter.Text);
gridView.DataSource = customers.ToArray();
gridView.DataBind();
}
This code uses the
Where
extension method instead of the
where
keyword. The first para-
meter of this generic method is an
IQueryable<T>
object, such as the
IQueryable<Customer>
in this example. An
IQueryable<T>
can be obtained from a regular
LINQ query or directly from the Customers property of the context object. The second
parameter of the
Where
method is a
lambda expression
, a mini-method that takes a
Customer as a parameter and returns a
Boolean
value that indicates whether or not it
matches the search condition.
LINQ allows you to compose queries from multiple parts. In this ongoing example, the
Where
method is first called if the user entered a search string for
City
, producing a SQL
query that looks like this:
select * from Customers where City = @City