Database Reference
In-Depth Information
var customers =
((IObjectContextAdapter)context).ObjectContext.CreateQuery<Customer>(esql, new[]
{
new ObjectParameter("Name",match),
new ObjectParameter("Skip",pageIndex * pageSize),
new ObjectParameter("Limit",pageSize)
});
foreach (var customer in customers)
{
Console.WriteLine("{0} [email: {1}]", customer.Name, customer.Email);
}
}
Following is the output from the code in Listing 3-26:
Customers Ro*
Roberts, Jill [email:
jroberts@abc.com
]
Robertson, Alice [email:
arob@gmail.com
]
Roe, Allen [email:
allenr@umc.com
]
Customers Ro*
Roberts, Jill [email:
jroberts@abc.com
]
Robertson, Alice [email:
arob@gmail.com
]
Roe, Allen [email:
allenr@umc.com
]
How It Works
In Listing 3-26, we show two different approaches to the problem. In the first approach, we use LINQ-To-Entities
extension methods to construct a LINQ query. We use the
Where()
method to filter the results to customers whose
last name starts with Ro. Because we are using the
StartsWith()
extension method inside the lambda expression, we
don't need to use a SQL wildcard expression such as “Ro%”.
After filtering, we use the
OrderBy()
method to order the results. Ordered results are required by the
Skip()
method. We use the
Skip()
method to move over
pageIndex
number of pages, each of size
pageSize
. We limit the
results with the
Take()
method. We only need to take one page of results.
Note that in this code block, we create the entire query using LINQ extension methods and not the SQL
query-like expressions that we have seen in examples up to now. Both the
Skip()
and
Take()
methods are only
exposed by extension methods, not query syntax.
For the second approach, we construct a complete, parameterized Entity SQL expression. This is perhaps the
most familiar way to solve the problem, but it exposes some of the inherent mismatch risks between a query language
expressed using strings and executable code expressed, in this case, in C#.
3-13. Grouping by Date
Problem
You have an entity type with a DateTime property, and you want to group instances of this type based on just the date
portion of the property.