I am trying to dynamically query Entity Framework, so I'm using the Expression class to put together a LambdaExpression that will be queried against an object set. If I have a reference to LambdaExpression, where I don't have an explicit function defined, is it possible to query against an objectset this way, or is it required to have a generic expression defined (using Expression.Lambda<..>)?
Thanks.
This is what I was looking to do:
http://msdn.microsoft.com/en-us/library/bb882637.aspx
Using this, I was able to build a lambda expression against an object set dynamically. Worked very well.
Check out Dynamic Linq. Basically you can use strings in place of LINQ expressions until you want to use them. Sounds like it might be what you want.
Related
When I write expressions in our application as lambda expressions, I can usually make use of the following construct1:
dbContext.Contents<MyEntity>()
(dbContext is of a custom class.)
Somehow, Linq1Entities/Entity Framework understands this to mean I am SELECTing items from the table matching MyEntity.
Now, I am constructing an expression by means of the System.Linq.Expressions classes.
I have tried to replicate the above fragment like so:
Expression.Call(Expression.Constant(dbContext), contentsMethod)
contentsMethod has been initialized to the appropriate MethodInfo before by means of reflection.
Unfortunately, this does not work.
Entity Framework complains that it cannot convert the dbContext object to SQL.
I have built an analogous expression of what I wanted as a lambda expression and looked at the resulting expression tree in the debugger.
Interestingly, instead of a constant, the dbContext was modeled as a member access of what seemed to be a closure object.
Why is that? Why is a local variable dbContext represented by a member access to the closure in an expression, and why doesn't it alternatively work as a constant value? Does it matter that dbContext was a parameter of the enclosing method in my case?
My question is not how to solve the issue.
I already did, by introducing the fragment shown above as an extra lambda expression whose body gets tied into my manually built expression.
1: An example of how that fragment is used is the following expression:
dbContext.Contents<MyEntity1>().Where(e1 => dbContext.Contents<MyEntity2>().Any(e2 => e1.Name == e2.Key))
dbContext is modeled as an access to a closure object because the lambda that defined it was closing over that variable. It wasn't using a constant value, it was closing over another value, so that's what it represented in the Expression. If it did anything else it wouldn't be properly representing the lambda.
When EF says that it can't convert an Expression to SQL it's simply saying that the authors of the code didn't anticipate the given expression, and didn't create a mapping of that pattern to SQL; they simply didn't anticipate people doing this (or didn't know how to map it to SQL, or couldn't, or didn't have the time to add that feature, whatever the case may be).
I could use some help with expression conversion.
I have a method on a class which looks like the following:
protected IQueryOver<TEntity, TEntity> OrderQuery<TOrderBy>(
Expression<Func<TEntity, TOrderBy>> orderBy)
{
return session.QueryOver<TEntity>().OrderBy(orderBy).Asc;
}
This is a generic query for a repository class. I want to keep things generic so I specified the TOrderBy parameter so that the type of the property doesn't matter. However, this implementation example is using NHibernate and I'm trying to do the following:
var query = session.QueryOver<TEntity>().OrderBy(orderBy).Asc;
However, ther OrderBy method takes a parameter of Expression> and therefore I get a compile error as there is no guarantee that TOrderBy would be an object.
Is there a way of doing this conversion or should I just stick with using object rather than TOrderBy? If I stick with object, do I not lose the ability to order by ValueTypes (e.g. DateTime)?
Thanks for any help/suggestions.
EDIT: I should mention, I have kept this generic as I will be writing implementations for nhibernate and entity framework. There isnt an issue with this in EF as it uses the normal Linq OrderBy method. It is just in the Nhibernate implementation I'm having this problem
If you are using LINQ with EF, why not use LINQ with NHibernate too instead of QueryOver?
Both snippets below product the same output.
I understand how Func encapsulates a method with a single parameter, and returns a bool value. And you can either assign it a
method, anonymous method or a lambda expression.
Func<int, bool> deleg = i => i < 5;
Console.WriteLine("deleg(4) = {0}", deleg(4));
Below is using expression trees which I don't fully understand yet. Why would I want to do it this way? Is it more flexible, what advantage does it give me?
System.Linq.Expressions.Expression<Func<int, bool>> expr = i => i < 5;
Func<int, bool> deleg2 = expr.Compile();
Console.WriteLine("deleg2(4) = {0}", deleg2(4));
Basically, the Expression tree is the body of a lambda expression, that allows you to
introspect the expression (see what's in it so to say)
manipulate the expression (simplify, extend (e.g. add new functionality or modify to work on different items).
Once you Compile() the expression, it is just another delegate, which you can only call, not inspect or modify.
Whenever you want to
create expressions dynamically (I mean: construct, not allocate)
operate on expressions dynamically
the Function<> types are not sufficient.
The point of expression trees is that you can do more with them than just compile them to a function. You can inspect them, modify them and compile them to something other than .net functions.
For example Linq2SQL compiles expression trees to SQL code. You couldn't do that with a plain .net function.
In your first example you just have "hardcoded" the body of the function and assigned it to a delegate.
In your second example the assignment constructs an expression-tree which is an object model reprensenting your code in a data structure in memory.
The advantage is that you can modify and inspect that datastructure.
LINQ2SQL for example uses that technique to translate your expressions to another language called SQL.
Expression trees are regular in-memory data structures that can be traversed programmatically and the result of such traversal can be something, like a query you'd like to send to the database. Read more on the ExpressionVisitor class to see how it is done.
On the other hand, the compiled function is nothing more than a sequence of CIL code. You still can inspect it programmatically but you are not inspecting the definition but rather - the compiler output of it.
Can anyone explain what is the use of expressions<func>?
I'm going to assume you mean Expression<Func> where Func is any variety of the generic Func delegate.
If this is to be the case, what Expression<Func> is doing is getting an expression tree of the lambda that you're passing in its place. You'll find this most commonly on the variants of IQueryable<T> or in many fluent interfaces.
The expression trees are used at run-time to generally translate the lambda expression into some other format. Such as SQL in the case of LINQ to SQL.
You can read up more on Expression
And more about expression trees in .NET
Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y
You can read more in this article.
From MSDN:
Represents a strongly typed lambda expression as a data structure in the form of an expression tree
Here's a real world example of it's use that shows why it's useful: http://www.albahari.com/nutshell/predicatebuilder.aspx
You may want to start here
A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.
For instance, if I want to map property Title I use:
> Map(x => x.Title);
That's weird because this delegate is only returning the value of the property and not the property itself while NHibernate needs to know the property itself.
How does it work?
Map is a function, that (among other things via overloads) takes a Expression<Func<T>> - i.e. it looks like a Func<T>, but Expression<Func<T>> gets converted into an expression tree instead of just the lambda.
Expression trees are basically ASTs, and you can write code to traverse an expression tree to extract a string with the property name, allowing you to reflect "normally" from then on.
There's a lot of stuff available where people write stuff that reflect on expression trees. Check out this post for example, for a demonstration on how to write a couple of utility methods to make the reflection easy.