lundi 11 janvier 2016

How do I build Expression Call for Any Method with generic parameter

I'm just trying make the same expression like below using Linq.Expression:

Expression<Func<Organization, bool>> expression = @org => @org.OrganizationFields.Any(a => a.CustomField.Name == field.Name && values.Contains(a.Value));

In this example above I have an entity called Organization and it has a property called OrganizationsFields as IEnumerable and I want to find any occurrence that match with Any parameter expression.

I just using the code below to generate expression dynamically:

string[] values = filter.GetValuesOrDefault();

ParameterExpression parameter = Expression.Parameter(typeof(T), "org");
Expression organizationFields = Expression.Property(parameter, "OrganizationFields");

MethodInfo any = typeof(Enumerable)
   .GetMethods()
   .FirstOrDefault(a => a.Name == "Any" && a.GetParameters().Count() == 2)
   .MakeGenericMethod(typeof(OrganizationField));

Func<OrganizationField, bool> functionExpression = a => a.CustomField.Name == filter.Name && values.Contains(a.Value);
Expression functionParam = Expression.Constant(functionExpression, typeof(Func<OrganizationField, bool>));

Expression call = Expression.Call(organizationFields, any, functionParam);

return Expression.Lambda<Func<T, bool>>(call, parameter);

The problems occur when I call the method Expression.Call it throw an ArgumentExeption

Can anyone help me?

Regards





Aucun commentaire:

Enregistrer un commentaire