'Contains()' workaround using Linq to Entities?

前端 未结 10 1962
清酒与你
清酒与你 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条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 14:57

    To complete the record, here's the code I finally used (error checking omitted for clarity)...

    // How the function is called
    var q = (from t in svc.OpenTransaction.Expand("Currency,LineItem")
             select t)
             .Where(BuildContainsExpression(tt => tt.OpenTransactionId, txnIds));
    
    
    
     // The function to build the contains expression
       static System.Linq.Expressions.Expression> BuildContainsExpression(
                    System.Linq.Expressions.Expression> valueSelector, 
                    IEnumerable values)
            {
                if (null == valueSelector) { throw new ArgumentNullException("valueSelector"); }
                if (null == values) { throw new ArgumentNullException("values"); }
                System.Linq.Expressions.ParameterExpression p = valueSelector.Parameters.Single();
    
                // p => valueSelector(p) == values[0] || valueSelector(p) == ...
                if (!values.Any())
                {
                    return e => false;
                }
    
                var equals = values.Select(value => (System.Linq.Expressions.Expression)System.Linq.Expressions.Expression.Equal(valueSelector.Body, System.Linq.Expressions.Expression.Constant(value, typeof(TValue))));
                var body = equals.Aggregate((accumulate, equal) => System.Linq.Expressions.Expression.Or(accumulate, equal));
                return System.Linq.Expressions.Expression.Lambda>(body, p);
            }
    

提交回复
热议问题