Send mail to the author(s) E-mail

# Friday, 17 October 2014
( Expression | Func | Linq )

Linq provider with translate linq to SQL (for EF)

Expressions wrap a Func type.

static void Main() { var db = new MovieDB(); IEnumerable<Movie> query = // Lambda expression being passed in - how to filter db.Movies.Where(m => m.Title.StartsWith("Wal")) // Lambda expression - how to filter .OrderBy(m => m.ReleaseDate.Year); foreach (var movie in query) { Console.WriteLine(movie.Title); }
Then look at profiler:

SELECT [Project1].[ID] AS [ID], [Project1].[Title] AS [Title], [Project1].[ReleaseDate] AS [ReleaseDate] FROM ( SELECT DATEPART (year, [Extent1].[ReleaseDate]) AS [C1], [Extent1].[ID] AS [ID], [Extent1].[Title] AS [Title], [Extent1].[ReleaseDate] AS [ReleaseDate] FROM [dbo].[Movies] AS [Extent1] WHERE [Extent1].[Title] LIKE N'Wal%' ) AS [Project1] ORDER BY [Project1].[C1] ASC

Outer query for ordering.  Sub query for filtering – StartsWith “Wal”

How do these Func’s get translated into Expressions that go into SQL Server?


Ahh, not selected the extension method for IEnumerable.

Using IQueryable (which derives from IEnumerable).  But all remote linq providers implmement properties which are IQueryable.

No longer take a Func<T>, but an Expression<T>.  Where T is a Func<T>


Opaque – only tells us it takes an int, and returns an int.  Doesn’t really see what's inside of that method.

Expression – essentially when the extension method for IQueryable is doing.

write(square(add(1, 3)));

Invoking the square Func no longer works. (method delegate or event is expected)


In immediate window:



NodeType is multiple, left hand side is x, right hand side is x.  Value to produce is Int32.

Compiler doesn’t compile lambda expression to IL, but builds a data structure – an abstract syntax tree, that have objects inside that represent the operations that we have expressed in code.

Up to linq provider to take the data structure and figure out how to translate it.

Comprehension Query Syntax

var query2 = from m in db.Movies where m.Title.StartsWith("L") select m;

C# compiler translates this syntax into extension method calls.

var q2 = db.Movies.Where(x => x.Title.StartsWith("L")) .OrderBy(x => x) .Select(x => x);

Many of these LINQ oriented features are useful for everyday code

  • Functional programming
  • Reduced noise
| | #