2

我需要创建一个表达式树,我可以将它作为子句中的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));
4

2 回答 2

3

谷歌了!

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);

它有效!

于 2012-11-24T15:59:57.000 回答
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);
}
于 2012-11-24T16:09:29.600 回答