Databases Reference
In-Depth Information
Notice how much easier it is to filter Product entities based on Supplier entity properties
with LINQ than it is with plain SQL. LINQ allows you to traverse the Supplier navigation
property and specify filter criteria for the parent entity without having to implement an
explicit join. Here is an equivalent query that looks closer to the INNER JOIN SQL state-
ment you would have to create without LINQ:
IQueryable<Product> query =
from p in context.Products
join s in context.Suppliers.Where(s => s.Country == “UK”)
on p.SupplierID equals s.SupplierID
select p;
Obviously, this query is more verbose and difficult to understand; it is unlikely you would
have chosen this approach when implementing custom filtering logic. However, it does
offer an important advantage over its predecessor when it comes to building queries
dynamically. By using an explicit join operator, this new query helps you to see that you
can combine two completely independent queries, context.Products and
context.Suppliers.Where(s => s.Country == “UK”) , to return a set of child, Product,
and entities filtered by search criteria applied to its parent entity, Supplier.
This is exactly how the Parent filter template works to fit into the constraints of the
Dynamic Data filtering architecture. The template receives the child query,
context.Products , has the nested filter template generate the parent query,
context.Suppliers.Where(s => s.Country == “UK”) , combines them with a join , and
uses a select to return just the child entities.
Unfortunately, Dynamic LINQ does not support the join operator, so you have to imple-
ment this logic from ground up with the LINQ expression API. This is, by far, the most
complex, error-prone, and time consuming programming task you will encounter when
building dynamic web applications. On the bright side, it helps you to gain a new level
appreciation of the heavy lifting that the C# and Visual Basic compilers do for you when
converting the magically simple LINQ queries to expressions.
To build a LINQ query dynamically, you have to be familiar with the extension method
syntax (as opposed to the language-integrated syntax) of building LINQ queries. LINQ
expressions are an object model that represents queries built with LINQ extension
methods. Because the language-integrated query syntax is a higher-level abstraction on
top of the extension methods, it is easier to make a mental jump from the LINQ extension
methods to LINQ expressions. Here is the same query, expressed with the LINQ extension
method, Join :
IQueryable<Product> query = Queryable.Join(
context.Products,
context.Suppliers.Where(s => s.Country == “UK”),
p => p.SupplierID,
s => s.SupplierID,
(p, s) => p);
Search WWH ::




Custom Search