Dynamic String based Queries in LINQ - Dynamic Expression API - Raj Kaimal

Dynamic String based Queries in LINQ - Dynamic Expression API

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).

The post uses a LINQ to SQL entity model for the NorthWind database in VS 2008, We create an instance of this model like so:

NorthwindDataContext context = new NorthwindDataContext();

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

var x = context
    .Customers
    .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:

string sortExpression = "ContactName DESC"; 
var x1 = context 
    .Customers
    .OrderBy(sortExpression);

The SQL generated in both cases will be

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle],
[t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [dbo].[Customers] AS [t0] 4: ORDER BY [t0].[ContactName] DESC

Moving on to another example, If I had a query like so,

DateTime myDate = Convert.ToDateTime("7/26/1996");
var y = context
    .Orders
    .Where(a => (a.Customer.Country == "Switzerland") && (a.OrderDate < myDate))
    .OrderBy(o=> o.OrderDate)
    .Select(o => new { o.Customer.ContactName, o.Customer.Country, o.OrderDate });

I could use the Dynamic Expression API to rewrite it like this:

var y1 = context
    .Orders
    .Where("Customer.Country == @0 and OrderDate < @1", "Switzerland", myDate)
    .OrderBy("OrderDate")
    .Select("new(Customer.ContactName,Customer.Country, OrderDate)");

Note that, in the query above, the shape of the result is specified as a string. Note also that I have defined what are known as substitution values in the Where statement.

The SQL generated in both cases would be:

exec sp_executesql N'SELECT [t1].[ContactName], [t1].[Country], [t0].[OrderDate] 
FROM [dbo].[Orders] AS [t0]
LEFT OUTER JOIN [dbo].[Customers] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE ([t1].[Country] = @p0) AND ([t0].[OrderDate] < @p1)
ORDER BY [t0].[OrderDate]' 6: N'@p0 nvarchar(11),@p1 datetime'
@p0=N'Switzerland',
@p1='1996-07-26 00:00:00:000'

To use the Dynamic Expression API, add the Dynamic.cs class to your project and import the System.Linq.Dynamic namespace.  

To learn more, download the LINQ and language samples for Visual Studio 2008 Beta 2 zip file located at the Visual Studio 2008 samples page.

Published Tuesday, September 18, 2007 12:21 AM by rajbk
Filed under: , ,

Comments

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

I created a similar framework on codeplex at http://www.codeplex.com/nlinq. The advantage is that it works on VS.NET 2003 & 2005.

Tuesday, September 18, 2007 2:23 AM by S&#233;bastien Ros

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

Hi,Raj, Where can I download the Dynamic.cs  file? I can't find it.

Monday, October 29, 2007 8:53 AM by cokkiy

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

Cokkiy,

Go to the samples page at the bottom of the post.

Monday, October 29, 2007 9:47 AM by rajbk

# LINQ : Paging and sorting LINQ Queries with a custom QueryDataSource

So you've got a LINQ query and now you want to drop it on a GridView. If you assign it to the datasource

Saturday, November 03, 2007 3:56 AM by Community Blogs

# LinqDataSource exceptions

Prerequisite: LinqDataSource &amp; SqlDataSource Master/Details When working with the LinqDataSource

Thursday, January 31, 2008 9:10 PM by Raj Kaimal

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

This is for DLinq how about linq?

Wednesday, March 26, 2008 10:57 PM by Ricky

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

I'm having trouble getting this to work with LINQ TO XML

It seems the dynamic namespace only extends the IQuereyable and not the IEnumerable.

Anybody managed to make this work with XML as the Data Source provider?

Friday, May 23, 2008 5:53 AM by Shereef

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

How can I use like to filter?

Thursday, July 24, 2008 12:28 PM by Renan

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

Can we use this for LINQ to XML queries as well. It will be very helpful if someone can post an example with LINQ to XML. I need to use Linq to XML and my queries are dynamically generated. Doing a switch case is not an option for me as the cases could be thousands. Any help is appreciated.

Thanks in advance.

Tajinder

Thursday, December 18, 2008 9:50 AM by Tajinder Sarao

# Custom Expressions and the DLR &ndash; Part 1 &laquo; Chris Cavanagh&#8217;s Blog

Pingback from  Custom Expressions and the DLR &ndash; Part 1 &laquo; Chris Cavanagh&#8217;s Blog

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

How do i use Dynamic Linq to query from a list like List<Customer> Customers = new List<Customer> {

                   new Customer {

                       CustomerID = 71,

                       Name = "Emma",

                       Email = "emz0r@worreva.com"

                   }

when i use a "where" it does not use IQueryable's where.

Sunday, March 29, 2009 2:54 AM by Kumar

# LINQ to SQL mapping

LINQ to SQL mapping

Tuesday, July 14, 2009 8:37 PM by Euforik

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

When I tried to compile my (web) application with Dynamic.cs, but the F-Secure application is stopping it from being built compianing that the applicationname.dll is infected with TROJAN.DROPPER.RVD? when I excluded the Dynamic.cs from project VS2008 built the application successfully.

Any Idea what's going on here?

Thanks & Regards,

Kishor

Friday, October 22, 2010 8:45 AM by kishor

# ????????????Lambda????????? | Hello VisualStudio

Pingback from  ????????????Lambda????????? | Hello VisualStudio

Tuesday, November 09, 2010 12:37 AM by ????????????Lambda????????? | Hello VisualStudio

# re: Dynamic String based Queries in LINQ - Dynamic Expression API

is it possible to use dynamic exp. in something like tihs :

Dim q = From line In File.ReadAllLines("c:\test.txt")

               Let CR = line.Split(vbTab)

               Select New With {.email = CR(0)}

a tabdelimited text file with varible fieldscount .

Saturday, November 13, 2010 4:50 AM by sadegh

# 我的技术网址藏 | Memory Stick

Pingback from  我的技术网址藏 | Memory Stick

Wednesday, February 23, 2011 2:09 AM by 我的技术网址藏 | Memory Stick

# sql statement to Expression tree | C Language Development | C Programming Language Tutorial

Pingback from  sql statement to Expression tree | C Language Development | C Programming Language Tutorial