zoukankan      html  css  js  c++  java
  • How do I write a LINQ to Entities query which has the equivalent of the SQL “in” keyword?

    In SQL, you might write a query that looks something like this: SELECT * FROM Foo WHERE blah IN (1, 3, 5, 7).  With LINQ to Entities you might have a similar scenario except that you are selecting from an entityset and the list of values you want to compare against is stored in a LIST<T>.  Unfortunately, the Entity Framework does not currently support collection-valued parameters.  To work around this restriction, you can manually construct an expression given a sequence of values using the following utility method:

    static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(

        Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> 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<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));

        return Expression.Lambda<Func<TElement, bool>>(body, p);

    }

    Using this utility method, you can rewrite:

    var query1 = from e in context.Entities

                 where ids.Contains(e.ID)

                 select e;

    as

    var query2 = context.Entities.Where(

        BuildContainsExpression<Entity, int>(e => e.ID, ids));      

  • 相关阅读:
    [gj]三国攻势图
    [svc]msmtp+mutt发附件,发邮件给多个人
    [sh]清理memcached缓存
    [svc]jdk1.7.0_13(系列)下载url
    [svc]linux查看主板型号及内存硬件信息
    [svc][op]如何查看当前Ubuntu系统的版本
    [svc][bg]phabricator-zh_CN汉化包
    [na]台式机装原版Win2008R2
    [svc]salt源码安装软件和yum安装软件
    JSTL的相关使用
  • 原文地址:https://www.cnblogs.com/ejiyuan/p/1518176.html
Copyright © 2011-2022 走看看