当前位置 > 首页 > Asp.net

Dynamic String based Queries in LINQ - Dynamic Expression API

9/18/2007 3:38:00 PM来源:Asp.net

Version: Visual Studio 2008 Beta 2

The Dynamic Expression API extends the core LINQ API with the ability to dynamically create string based queries that are constructed at run-time. The API provides

  • Dynamic parsing of strings to produce expression trees (the ParseLambda and Parse methods),
  • Dynamic creation of “Data Classes” (the CreateClass methods), and
  • Dynamic string-based querying through LINQ providers (the IQueryable extension methods).

Assuming I have created a LINQ to SQL entity model for the NorthWind database in VS 2008,

 1: NorthwindDataContext context = new NorthwindDataContext();

I normally would write a query to return all customers ordered by the ContactName in descending order like so:

 1: var x = context.
 2: Customers.
 3: OrderByDescending(c => c.ContactName);

If instead, I wanted to define the Sort column and Sort direction in a string, I could rewrite the query, with the help of the Dynamic Expression API, like so:

 1: string sortExpression = "ContactName DESC";
 2: var x1 = context.
 3: Customers.