Having problems with scope of lambda expressions - c#

Let's use this method that I'm trying to call as an example:
MyMethod<MyType, string>(Expression<Func<MyType, string>> expression)
If I try to dynamically build the following expression x => x.Name and pass it to the method, everything works just fine:
var pi = typeof(MyType).GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
MemberExpression me = Expression.Property(pe, pi);
var exp = Expression.Lambda(me, pe);
Now let's imagine that in the exact same scope, I'm trying to build this expression instead x => item.Name using the following code, obviously item being different than the input parameter x:
var item = new MyType() { Name = "My name" };
var pi = t.GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
ParameterExpression pe2 = Expression.Parameter(typeof(MyType), "item");
MemberExpression me = Expression.Property(pe2, pi);
var exp = Expression.Lambda(me, pe);
When I try to call MyMethod I get the following error, probably because there's no variable "item" in the scope where MyMethod is called (which is not where I build the expression):
variable 'item' of type 'MyType' referenced from scope '', but it is not defined
How can I build this expression in such a way that it won't throw this error?

Within the scope of the lambda, the item bit is a constant - it's not a variable parameter to the invocation.
So the following should be closer:
var item = new MyType() { Name = "My name" };
var pi = t.GetProperty("Name");
ParameterExpression pe = Expression.Parameter(typeof(MyType), "x");
ConstantExpression ce = Expression.Constant(typeof(MyType), item);
MemberExpression me = Expression.Property(ce, pi);
var exp = Expression.Lambda(me, pe);

The string "item" is not related in any way to the local variable item. If you want your constructed lambda expression to capture the value of the local variable item, then instead of Expression.Parameter(typeof(MyType), "item") you need Expression.Constant(item).

Related

C# Building an Action Expression with a code block

I am tying to build an Expression tree that would represent this lambda:
Action<TFrom, TTo> map =
(from, to) =>
{
to.Property1 = (Nullable<TTo>)from.Property1;
to.Property2 = (Nullable<TTo>)from.Property2;
// ...continued for all properties
};
Essentially, I am trying to map the non-nullable properties from one class to the Nullable<T> properties of another class that share the same property name.
I have written this (incorrect) tree in my attempt to do this:
SomeObjWithOutNullable i = new SomeObjWithOutNullable(); // Not "object".. doh
SomeObjWithNullable j = new SomeObjWithNullable();
ParameterExpression p1 = Expression.Parameter(typeof(SomeObjWithOutNullable), "from");
ParameterExpression p2 = Expression.Parameter(typeof(SomeObjWithNullable), "to");
MemberExpression m1 = Expression.PropertyOrField(p1, "Property1");
MemberExpression m2 = Expression.PropertyOrField(p2, "Property1");
BinaryExpression body = Expression.Assign(m1, m2);
LambdaExpression lambda = Expression.Lambda<Action<SomeObjWithOutNullable,SomeObjWithNullable>>(body, new[] { p1,p2 });
var action = lambda.Compile();
action(i,j);
This does not compile. I get this exception when I attempt to:
Delegate 'System.Action<SomeObjWithOutNullable,SomeObjWithNullable>' has some invalid arguments
Argument 1: cannot convert from 'object' to 'SomeObjWithNullable'
Argument 2: cannot convert from 'object' to 'SomeObjWithNullable'
I know I have yet to add in the type conversion, but I cannot seem to figure out how to do even the assignment correctly.
Ok, I found the solution:
void NullPropertyConvertionAction<TSource, TTarget>(TSource source, TTarget target)
{
var sourceDictionary = typeof(TSource).GetProperties()
.ToDictionary(s =>
s.Name.
StringComparer.InvariantCultureIgnoreCase
);
ParameterExpression p1 = Expression.Parameter(typeof(TSource), "from");
ParameterExpression p2 = Expression.Parameter(typeof(TTarget), "to");
var expressionBodies = new List<BinaryExpression>();
foreach (var member in typeof(TTarget).GetProperties()
.Where(p=> p.PropertyType.IsGenericType
&& p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
if (sourceDictionary.ContainsKey(member.Name))
{
MemberExpression m1 = Expression.PropertyOrField(p1, sourceDictionary[member.Name].Name);
MemberExpression m2 = Expression.PropertyOrField(p2, member.Name);
BinaryExpression body = Expression.Assign(m2, Expression.Convert(m1, member.PropertyType));
expressionBodies.Add(body);
}
}
BlockExpression block = Expression.Block(expressionBodies.ToArray());
LambdaExpression lambda = Expression.Lambda<Action<TSource,TTarget (block, new[] { p1,p2 });
Action<TSource,TTarget> action = (Action<TSource,TTarget>)lambda.Compile();
action(source,target);
}
You've thrown away the type information when you downcast your lambda to LambdaExpression. The easiest way to solve this would be to use var:
var lambda = Expression.Lambda ...
Alternatively, use the full correct type:
Expression<Action<TSource, TTarget>> lambda = Expression.Lambda ...

Dynamic lambda expression for array property filter

As per requirement I want to create a dynamic lambda expression using C#.
For example I want to generate the dynamic query like
Employee. Address[1].City
How can I do this? Please note that the property is a dynamic one.
I have tried this code
var item = Expression.Parameter(typeof(Employee), "item");
Expression prop = Expression.Property(item, "Address", new Expression[] { Expression.Constant[1] });
prop = Expression.Property(prop, "City");
var propValue = Expression.Constant(constraintItem.State);
var expression = Expression.Equal(prop, propValue);
var lambda = Expression.Lambda<Func<Line, bool>>(expression, item);
But it did not work.
Any help would be appreciated.
Thanks.
You "dynamic query" expression (which is not really a query, it's a simple MemberExpression) can be produced as follows:
ParameterExpression param = Expression.Parameter(typeof(Employee), "item");
MemberExpression address = Expression.Property(param, "Address");
BinaryExpression indexedAddress = Expression.ArrayIndex(address, Expression.Constant(1));
MemberExpression city = Expression.Property(indexedAddress, "City"); // Assuming "City" is a string.
// This will give us: item => item.Address[1].City
Expression<Func<Employee, string>> memberAccessLambda = Expression.Lambda<Func<Employee, string>>(city, param);
If you want an actual predicate to use as part of your query, you just wrap the MemberExpression with a relevant compare expression, i.e.
BinaryExpression eq = Expression.Equal(city, Expression.Constant("New York"));
// This will give us: item => item.Address[1].City == "New York"
Expression<Func<Employee, bool>> predicateLambda = Expression.Lambda<Func<Employee, bool>>(eq, param);
In terms of your code: not sure why you're creating a lambda where the delegate type is Func<Line, bool> when the input is clearly expected to be Employee. Parameter type must always match the delegate signature.
EDIT
Non-array indexer access example:
ParameterExpression param = Expression.Parameter(typeof(Employee), "item");
MemberExpression address = Expression.Property(param, "Address");
IndexExpression indexedAddress = Expression.MakeIndex(
address,
indexer: typeof(List<string>).GetProperty("Item", returnType: typeof(string), types: new[] { typeof(int) }),
arguments: new[] { Expression.Constant(1) }
);
// Produces item => item.Address[1].
Expression<Func<Employee, string>> lambda = Expression.Lambda<Func<Employee, string>>(indexedAddress, param);
// Predicate (item => item.Address[1] == "Place"):
BinaryExpression eq = Expression.Equal(indexedAddress, Expression.Constant("Place"));
Expression<Func<Employee, bool>> predicateLambda = Expression.Lambda<Func<Employee, bool>>(eq, param);

How to Create an Expression tree for .Where(x => x.<deep property>.Select(y => y.id).Intersect(List<int>).Any())

I'm creating a method that receives a Queryable<T> source, a string with a property name/path (could be a deep property for example "TrParent.DataTypes" to achieve this x => x.TrParent.DataTypes) and Enumerable<int> which holds the values I need to intersect.
Basically I come from the need to create the following query dynamically (I mean <DT_Det_Tr> and TrParent.DataTypes being know only at runtime, in the example DT_Det_Tr is not a type it is a class):
var _vals = new List<int>();
var res = dbContext.Set<DT_Det_Tr>()
.Where
(x => x.TrParent.DataTypes
.Select(t => t.Id)
.Intersect(_vals)
.Any()
);
Please keep in mind that the preceding query is just an example of what I need to achieve dynamically, what I really need is an expression tree that creates a predicate like the one shown above but using a dynamic type and with the deep navigation property specified within a string.
So, I'm using this function to create the expression for the deep property:
private static LambdaExpression CreateDelegateExpression<T>(out Type resultingtype, string property, string parameterName = "x")
{
var type = typeof(T);
ParameterExpression param = Expression.Parameter(type, parameterName);
Expression expr = param;
foreach (string prop in property.Split('.'))
{
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, param);
resultingtype = type;
return lambda;
}
And here is what I have so far for my function:
public static IQueryable<T> Intersect<T>(this IQueryable<T> source, string property, IEnumerable<int> value)
{
//List of ids
var _value = Expression.Constant(value);
//Get delegate expression to the deep property and it's inner type
Type type = null;
var lambda = CreateDelegateExpression<T>(out type, property, "x");
var enumtype = type.GetGenericArguments()[0];
ParameterExpression tpe = Expression.Parameter(enumtype, "y");
Expression propExp = Expression.Property(tpe, enumtype.GetProperty("Id"));
MethodInfo innermethod = typeof(Queryable).GetMethods().Where(x => x.Name == "Select").First();
//Error on next line...
var selectCall = Expression.Call(typeof(Queryable),
"Select",
new Type[] { enumtype, typeof(long) },
lambda,
propExp);
//TODO: Add rest of logic and actually filter the source
return source;
}
In the var selectCall = line I'm getting error:
No generic method 'Select' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.
I've read a lot here on SO and other sites but I can't get past this part, I feel I'm going to bump into more trouble when I get to the .Intersect(List<int>).Any() part so any help on that also would be grand, thanks.
After a lot of thought, investigation and attempts I came up with a solution.
First, I made a simpler version of my goal query (the static example I used in my question), so instead of:
var res = dbContext.Set<DT_Det_Tr>()
.Where
(x => x.TrParent.DataTypes
.Select(t => t.Id)
.Intersect(_vals)
.Any()
);
I made this:
var res = dbContext.Set<DT_Det_Tr>()
.Where
(x => x.TrParent.DataTypes
.Any(y => _vals.Contains(y.Id))
);
Which is a lot easier to translate to expressions (or at least it was for me) because it omits the Select call.
I got rid of the method I was using to create the deep navigation property expression and streamlined it in my Intersect function, this was because it was doing some work I don't really need here plus I needed access to some of the variables I use inside it, then I made this:
public static IQueryable<T> Intersect<T>(this IQueryable<T> source, string property, IEnumerable<int> value)
{
var type = typeof(T);
var _value = Expression.Constant(value); //List of ids
//Declare parameter for outer lambda
ParameterExpression param = Expression.Parameter(type, "x");
//Outer Lambda
Expression expr = param;
foreach (string prop in property.Split('.')) //Dig for deep property
{
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
//Get deep property's type
var enumtype = type.GetGenericArguments()[0];
//Declare parameter for inner lambda
ParameterExpression tpe = Expression.Parameter(enumtype, "y");
//Inner Collection lambda logic
//Property for inner lambda
Expression propExp = Expression.Property(tpe, enumtype.GetProperty("Id"));
//Contains method call .Contains(y.Id)
var containsMethodExp = Expression.Call(typeof(Enumerable), "Contains", new[] { propExp.Type }, _value, propExp);
//Create Expression<Func<enumtype, bool>>
var innerDelegateType = typeof(Func<,>).MakeGenericType(enumtype, typeof(bool));
//Create Inner lambda y => _vals.Contains(y.Id)
var innerFunction = Expression.Lambda(innerDelegateType, containsMethodExp, tpe);
//Get Any method info
var anyMethod = typeof(Enumerable).GetMethods().Where(m => m.Name == "Any" && m.GetParameters().Length == 2).Single().MakeGenericMethod(enumtype);
//Call Any with inner function .Any(y => _vals.Contains(y.Id))
var outerFunction = Expression.Call(anyMethod, expr, innerFunction);
//Call Where
MethodCallExpression whereCallExpression = Expression.Call
(
typeof(Queryable),
"Where",
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<T, bool>>(outerFunction, new ParameterExpression[] { param })
);
//Create and return query
return source.Provider.CreateQuery<T>(whereCallExpression);
}
I hope this helps anyone trying to develop a similar solution.
Working with expression trees can be very hard and frustrating at first, but it's a really powerful tool once you get the hold of it.
If you have access to the dynamic keyword from c# 4.0, you might be able to work around the problem like this:
var _vals = new List<int>();
var res = dbContext.Set<DT_Det_Tr>()
.Where(obj => { dynamic x = obj;
return x.TrParent.DataTypes
.Select(t => t.Id)
.Intersect(_vals)
.Any();
}
);
But I don't know enough about the details of the problem you want to solve to say for sure.

Building Expression Tree for string.Contains [duplicate]

This question already has answers here:
How do I create an expression tree to represent 'String.Contains("term")' in C#?
(4 answers)
Closed 9 years ago.
I'm struggling to build an expression tree so I can dynamically do filtering on some data.
I have come up with this, but it fails at the var lambda = line
foreach (var rule in request.Where.Rules)
{
var parameterExpression = Expression.Parameter(typeof(string), rule.Field);
var left = Expression.Call(parameterExpression, typeof(string).GetMethod("ToLower", Type.EmptyTypes));
var right = Expression.Constant(rule.Data.ToLower());
var method = typeof(string).GetMethod("Contains", new [] { typeof(string) });
var call = Expression.Call(left, method, right);
var lambda = Expression.Lambda<Func<T, bool>>(call, parameterExpression);
query = query.Where(lambda);
}
The var rule has a Field (ex "Name") which I want to compare with the text in rule.Data (ex 'tom'). So if T.Name.Contains("tom"); I want the query to include the record, otherwise, not.
The var query is of type IQueryable<T>
EDIT: Finally got it working with this code:
foreach (var rule in request.Where.Rules)
{
var parameter = Expression.Parameter(typeof(T), "x");
var property = Expression.Property(parameter, rule.Field);
var value = Expression.Constant(rule.Data);
var type = value.Type;
var containsmethod = type.GetMethod("Contains", new[] { typeof(string) });
var call = Expression.Call(property, containsmethod, value);
var lambda = Expression.Lambda<Func<T, bool>>(call, parameter);
query = query.Where(lambda);
}
You are almost there, but your parameter expression should be of type T, not String, you are also missing the expression that is getting the property from type T like name.
What you should roughly have is this
val -> Expression.Constant(typeof(string), rule.Field)
parameter -> Expression.Parameter(typeof(T), "p")
property -> Expression.Property(parameter, "PropertyName")
contains -> Expression.Call(property, containsmethod, val)
equals true -> Expression.True or equals, something like that
I am freehanding all of that, so it's likely somewhat different to be valid. The resulting expression should be something like this
p => p.Name.Contains(val)
If you want to create Where query, you must create lambda then call Where on query and pass lambda.
Try this:
Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, parameter);
MethodCallExpression expression = Expression.Call(typeof(Queryable), "Where",
new[] { typeof(T) }, query.Expression, lambda);
query = query.Provider.CreateQuery<T>(expression);
instead of
var result = Expression.IsTrue(call);
query = query.Provider.CreateQuery<T>(result);

Creating dynamic Expression<Func<T,Y>>

I want to create a dynamic Expression<Func<T,Y>>. Here is the code which works for string but doesn't work for DateTime. By doesn't work I mean, I get this exception:
"Expression of type 'System.Nullable`1[System.DateTime]' cannot be
used for return type 'System.Object'"
Can anybody analyze the mistake?
Type type = typeof(DSVPNProjection);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
PropertyInfo propertyInfo = type.GetProperty(sidx);
expr = Expression.Property(expr, propertyInfo);
var expression =
Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);
Do I need to change the object to some other type? If yes, then which? As you can see I am trying to dynamically fetch the PropertyInfo and use that as the 2nd parameter in Func.
For value types, you need to perform the boxing explicitly (i.e. convert to Object):
Type type = typeof(DSVPNProjection);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = null;
PropertyInfo propertyInfo = type.GetProperty(sidx);
expr = Expression.Property(arg, propertyInfo);
if (propertyInfo.PropertyType.IsValueType)
expr = Expression.Convert(expr, typeof(object));
var expression =
Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);

Categories