'Contains()' workaround using Linq to Entities?

前端 未结 10 2071
清酒与你
清酒与你 2020-11-22 14:01

I\'m trying to create a query which uses a list of ids in the where clause, using the Silverlight ADO.Net Data Services client api (and therefore Linq To Entities). Does any

10条回答
  •  旧时难觅i
    2020-11-22 14:43

    From MSDN:

    static Expression> BuildContainsExpression(
        Expression> valueSelector, IEnumerable values)
    {
        if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
        if (null == values) { throw new ArgumentNullException("values"); }
        ParameterExpression p = valueSelector.Parameters.Single();
    
        // p => valueSelector(p) == values[0] || valueSelector(p) == ...
        if (!values.Any())
        {
            return e => false;
        }
    
        var equals = values.Select(
                 value => (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
    
        var body = equals.Aggregate((accumulate, equal) => Expression.Or(accumulate, equal));
    
        return Expression.Lambda>(body, p);
    } 
    

    and the query becomes:

    var query2 = context.Entities.Where(BuildContainsExpression(e => e.ID, ids));
    

提交回复
热议问题