我只是尝试使用Linq.Expression创建如下表达式:
Expression> expression = @org => @org.OrganizationFields.Any(a => a.CustomField.Name == field.Name && values.Contains(a.Value));
在上面的这个例子中,我有一个名为Organization的实体,它有一个名为OrganizationsFields的属性作为IEnumerable,我想找到任何与Any参数表达式匹配的事件.
我只是使用下面的代码动态生成表达式:
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)); FuncfunctionExpression = a => a.CustomField.Name == filter.Name && values.Contains(a.Value); Expression functionParam = Expression.Constant( functionExpression, typeof(Func )); Expression call = Expression.Call(organizationFields, any, functionParam); return Expression.Lambda >(call, parameter);
当我调用方法Expression.Call它抛出一个ArgumentExeption时会出现问题
谁能帮我?
问候
干得好
var org = Expression.Parameter(typeof(Organization), "org"); Expression> predicate = a => a.CustomField.Name == filter.Name && values.Contains(a.Value); var body = Expression.Call(typeof(Enumerable), "Any", new[] { typeof(OrganizationField) }, Expression.PropertyOrField(org, "OrganizationFields"), predicate); var lambda = Expression.Lambda >(body, org);
必要部分(包括你的帖子标题)是以下有用的Expression.Call
重载
public static MethodCallExpression Call( Type type, string methodName, Type[] typeArguments, params Expression[] arguments )
还要注意,必须将predicate
参数Any
传递给Expression.Call
as Expression
.