I have a Group by expression that I am dynamically creating for use in a LINQ query. Currently, to construct the expression, I use the following code:
var arg = Expression.Parameter(typeof(T), helper.getName());
var prop = Expression.Property(arg, "customerType");
var body = Expression.Convert(prop, typeof(object));
var lambda = Expression.Lambda<Func<Contact, object>>(body, arg);
var keySelector = lambda.Compile();
I then use the keySelector in the GroupBy for my LINQ query. My question is, if I wanted to add a second grouping criteria to this expression, say "salesStage", how would I add that to this existing expression?
You have a problem, because what the compiler does on a regular GroupBy call is generate a new anonymous type with the properties you define. If the type doesn't exist, we cannot create an expression creating an object of the type.
However, given that you are using this for LINQ-to-Objects, we can use the Tuple<> type to generate the grouping key. Hopefully you do not need to group on more than 8 parameters.
Here is a generic function to generate the grouping function:
static Func<T, object> BuildGrouper<T>(IEnumerable<string> properties) {
var arg = Expression.Parameter(typeof(T), helper.getName());
// This is the list of property accesses we will be using
var parameters = properties.Select(propName => Expression.Property(arg, propName)).ToList();
// Find the correct overload of Tuple.Create.
// This will throw if the number of parameters is more than 8!
var method = typeof(Tuple).GetMethods().Where(m => m.Name == "Create" && m.GetParameters().Length == parameters.Count).Single();
// But it is a generic method, we need to specify the types of each of the arguments
var paramTypes = parameters.Select(p => p.Type).ToArray();
method = method.MakeGenericMethod(paramTypes);
// Invoke the Tuple.Create method and return the Func
var call = Expression.Call(null, method, parameters);
var lambda = Expression.Lambda<Func<T, object>>(call, arg);
return lambda.Compile();
}
Related
My goal is to support sorting in an application and expose it via REST API that would accept the parameter as a string.
Current implementation is along the lines of this:
GetUsers (Expression<Func<User, int>> sortExpression) {
// Retrieve users ...
return users.orderBy(sortExpression);
}
Usage example:
var users = GetUsers(u => u.Id);
the Expression<Func<User, int>> sortExpression is widely used in our repository and changing it would be difficult.
What I'd like to do is to be able to swap the u => u.Id with something that is generated during run-time.
Something that I have so far is:
// sortBy is retrieved from the calling method.
var type = typeof(User).GetProperties().FirstOrDefault(x => x.Name == sortBy).GetType();
var sortExpression = Expression.Property(Expression.Parameter(typeof(User)), sortBy);
var parameter = Expression.Parameter(typeof(User));
var expressionBody = Expression.Lambda(typeof(Func<User, int>), sortExpression, parameter);
var users = GetUsers(expressionBody)
I can see at run-time that this does create an expression that fits my needs, but the error is Argument 5: cannot convert from 'LambdaExpression' to 'Expression<System.Func<User, int>>' even though the body of the expression is supposed to be set by typeof(Func<User, int>)
I've figured out what I've been doing wrong.
First: Create the expression body using generic method
// Generic Method, return type Expression<Func<User, int>>
Expression.Lambda<Func<User, int>>(sortExpression, parameter);
Instead of passing the typeof(Func<User, int>) parameter.
// Non-generic. Return type LambdaExpression
Expression.Lambda(typeof(Func<User, int>), sortExpression, parameter);
Second:
I wasn't binding the parameter properly, which made it so that the expression was accessing property of a discarded parameter that wasn't provided to the expression.
// I'm creating an expression to access the property of a newly created parameter.
var sortExpression = Expression.Property(Expression.Parameter(typeof(User)), sortBy);
var parameter = Expression.Parameter(typeof(User));
var expressionBody = Expression.Lambda<Func<User, int>>(sortExpression, parameter);
//Above causes an unbinded variable exception since there are two parameters, one of which is not passed/bound.
//Should be:
var parameter = Expression.Parameter(typeof(User));
var sortExpression = Expression.Property(parameter, sortBy);
I'm trying to build an dynamic expression from a string of property-names (given by the user) on an IQueryable named source.
This is what I have so far:
var parameter = Expression.Parameter(source.ElementType, "x");
var member = propertyChain.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
var selector = Expression.Lambda(member, parameter);
which will give me something like x => x.MainProperty.SubProperty when the input would be MainProperty.SubProperty.
I now need to add ToString() to the expression selector so it will produce the expression x => x.MainProperty.SubProperty.ToString() which then can be passed into other methods.
How can this be done?
Edit 1
I'm trying to build a dynamic GroupBy where the type of the key doesn't matter. But the property to group by can be of type Guid, int or something else. That's why I need to call ToString().
public static IEnumerable<IGrouping<string, T>>(IQueryable<T> source, string propertyChain)
{
var parameter = Expression.Parameter(source.ElementType, "x");
var member = propertyChain.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
var selector = Expression.Lambda(member, parameter);
// currently here I have x => x.MainProperty.SubProperty
// here I would Invoke the GroupBy of IQueryable with T and string via reflection
}
You can use the following Expression.Call overload for instance:
var toString = Expression.Call(member, "ToString", Type.EmptyTypes);
var selector = Expression.Lambda<Func<T, string>>(toString, parameter);
return source.GroupBy(selector);
I am trying to dynamically configure Moq using reflection as per Dynamically calling Moq Setup() at runtime
In the example they use
var body = Expression.PropertyOrField( parameter, "ExampleProperty" );
To create an expression to select the desired property on the object and then construct a lambda expression using that selector.
I would like my selector to select a method instead, eg I want to dynamically construct the following:
mock.Setup(m => m.MyMethod()).Returns(1);
I have tried using:
var body = Expression.PropertyOrField(parameter, "MyMethod");
and
var body = Expression.MakeMemberAccess(parameter, typeof(T).GetMethod("MyMethod"));
but both seem to only work on properties or fields, is there a different selector I can use to select a method instead?
Full code below:
var mock = new Mock<T>();
var parameter = Expression.Parameter(typeof(T));
if (typeof(T).GetMethod("MyMethod") != null)
{
var body = Expression.PropertyOrField(parameter, "MyMethod");
var lambdaExpression = Expression.Lambda<Func<T, int>>(body, parameter);
mock.Setup(lambdaExpression).Returns(0);
}
While I don't have ready access to Moq here, I can show you how to build a lambda expression which invokes a method
private void DoIt<T>()
{
var mock = new Mock<T>();
var parameter = Expression.Parameter(typeof(T));
var methodInfo = typeof(T).GetMethod("MyMethod"); //Find the method "MyMethod" on type "T"
if (methodInfo != null)
{
var body = Expression.Call(parameter, methodInfo);
var lambdaExpression = Expression.Lambda<Func<T, int>>(body, parameter);
//At this point, lambdaExpression is:
//Param_0 => Param_0.MyMethod()
mock.Setup(lambdaExpression).Returns(0);
}
}
class MyClass
{
public int MyMethod()
{
return 5;
}
}
Note that typeof(T).GetMethod("MyMethod") is not very specific. There are plenty of overloads you can use (or leverage GetMethods and filter) that will allow you to specify the method by name, return type and parameter types.
Also, be aware the Expression.Lambda<Func<T, int>> will only work for methods with no parameters which return an int. Depending on who's responsible for determining the method, you may want to have this configurable, too.
What I want basically is to be able to to the following (following is psuedo code)
string SelectField = cb1.Name.Substring(2);
MyContext.Items.Select(x=>x.SelectField )
I tried the following:
string SelectField = cb1.Name.Substring(2);
ParameterExpression pe = Expression.Parameter(typeof(Item), "p");
var expr = Expression.Lambda(Expression.Property(pe, SelectField), pe);
query = MyContext.Items.Select(p=>expr)
but it gave me the error:
The LINQ expression node type 'Lambda' is not supported in LINQ to Entities.
Is this possible? I just want to be able to select a single entity property based on the selection of my combobox.
I was able to get my desired results using the following code (not much different then my original attempt)
string SelectField = cb1.Name.Substring(2);
ParameterExpression pe = Expression.Parameter(typeof(Item), "p");
Expression expr = Expression.Lambda(Expression.Property(pe, SelectField), pe);
Expression<Func<Item, string>> expression = (Expression<Func<Item, string>>)expr;
var query = MyContext.Items.Select(expression);
All I was missing was the Func line. It now works as I wanted.
Ok, so with this type of solution you're likely going to have to do a bunch of reflection to get it to work dynamically.
string SelectField = cb1.Name.Substring(2);
ParameterExpression pe = Expression.Parameter(typeof(Item), "p");
First you have to invoke the lambda method without knowing the complete return type. The return type is Expression<Func<Item, ?>> (with the question mark being a placeholder for the property type.
var propertyType = typeof(Item).GetProperty(SelectField).GetGetMethod().ReturnType;
var lambdaMethodParamType = typeof(Func<,>).MakeGenericType(typeof(Item), propertyType);
var lambdaMethod = typeof(Expression).GetMethods().First(x => x.Name == "Lambda" && x.IsGenericMethod).MakeGenericMethod(lambdaMethodParamType);
var expr = lambdaMethod.Invoke(null, new object[] { Expression.Property(pe, SelectField), new ParameterExpression[] { pe } });
Then we have to invoke the select method in a similar fashion because the property type isn't know until runtime.
var selectMethod = typeof(Queryable).GetMethods().First(x => x.Name == "Select").MakeGenericMethod(typeof(Item), propertyType);
var query = (IQueryable)selectMethod.Invoke(null, new object[] { MyContext.Items, expr });
I don't know what you're doing with the query variable so I can't provide any further guidance with that at this time. Again, in this example we don't know what type will be contained in the collection until runtime because it is a collection of the property values.
FYI: My method for selecting the correct lambda and select was a total hack. You really should create a more robust search method examing the signature more completely to ensure you've found the correct method you are needing. I can provide a better example later if you need it when I have more time.
This is the code I need to alter:
var xParam = Expression.Parameter(typeof(E), typeof(E).Name);
MemberExpression leftExpr = MemberExpression.Property(xParam, this._KeyProperty);
Expression rightExpr = Expression.Constant(id);
BinaryExpression binaryExpr = MemberExpression.Equal(leftExpr, rightExpr);
//Create Lambda Expression for the selection
Expression<Func<E, bool>> lambdaExpr = Expression.Lambda<Func<E, bool>>(binaryExpr, new ParameterExpression[] { xParam });
Right now the expression I'm getting out of this is (x => x.RowId == id) and what I want to change it to is (x => x.RowId) so that I can use it in an OrderBy for the ObjectContext.CreateQuery(T) method called later on.
Does anyone know how to change the above code so the lambda is correct to use in an OrderBy to order by the ID field?
Side Notes: The RowId is coming from this._KeyProperty I believe. This is part of a generic repository using the entity framework on Asp.Net MVC
Just omit creating the constant and "=":
var xParam = Expression.Parameter(typeof(E), "x");
var propertyAccessExpr = Expression.Property(xParam, this._KeyProperty);
var lambdaExpr = Expression.Lambda<Func<E, bool>>(propertyAccessExpr, xParam);
This assumes that _KeyProperty has type 'bool'. If it has a different type, just change Func<E, bool> to the appropriate type.
(Edited to incorporate asgerhallas and LukLed's good suggestions)