我需要创建一个表达式树,我可以将predicate
子句中的Where
参数传递给Linq To Enities查询。
public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate);
表达式树必须等同于以下指定的where子句:
var query = context.Products.Select(product =>
new { product.Name, product.Color });
var arr = "Red;Black".Split(';');
query = query.Where(obj => arr.Contains(obj.Color));
答案 0 :(得分:2)
用Google搜索出来了!
var paramExpr = Expression.Parameter(typeof(TSource), "src");
var memberExpr = (MemberExpression)property.Body;
List<Expression> arrayInits = new List<Expression>();
var arrExpr = Expression.Constant(((string)values[0]).Split(new char[] { ';' }));
MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");
var containsExpression = Expression.Call(null, contains, arrExpr, memberExpr);
var containsLambda = Expression.Lambda<Func<TSource, bool>>(containsExpression, property.Parameters);
它有效!
答案 1 :(得分:0)
public static Expression<Func<T, bool>> CreateContainsExpression<T>(T obj, string[] array)
{
var paramExpr = Expression.Parameter(typeof(T), "obj");
var arrExpr = Expression.Constant(array);
var colourPropExpr = Expression.Property(paramExpr, "Color");
MethodInfo containsMethod = typeof(ICollection<string>).GetMethod("Contains");
var containsExpr = Expression.Call(arrExpr, containsMethod, colourPropExpr);
return Expression.Lambda<Func<T, bool>>(containsExpr, paramExpr);
}