An Expression
is code representing code. It is not an executable piece of code that you can run until you call Compile()
.
An Expression
contains an object graph that describes some code. So the example function:
x => x + 1
Is representing a function that takes 1 parameter, and returns the expression (x + 1). As an object graph, it's something like this:
Expression
AdditionExpression
RightValue
VariableExpression (x)
LeftValue
LiteralExpression (1)
You could parse through the expression and figure out the name of the parts of the expression, or what the literal value is, or what the operation is. Once it is compiled, it is a logical sequence of operations, and all of that metadata is lost.
In terms of Entity Framework, given a sample expression like so:
myObjects.Where(x => x.Id > 10).ToList()
The LINQ to SQL IQueryable
provider is inspecting this expression, finding the name of the property Id
and then finding the literal value of 10 to convert that into a SQL statement. If this was a function (a compiled unit of code), there is no metadata to inspect, and conversion to SQL would be impossible. It also allows you to deconstruct things into supported and unsupported expressions for efficiency in making sure your SQL query returns the requested data only, instead of a large data set.