'Contains()' workaround using Linq to Entities?

前端 未结 10 2149
清酒与你
清酒与你 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:31

    Update: EF ≥ 4 supports Contains directly (Checkout Any), so you don't need any workaround.

    public static IQueryable WhereIn
      (
        this ObjectQuery query,
        Expression> selector,
        IEnumerable collection
      )
    {
      if (selector == null) throw new ArgumentNullException("selector");
      if (collection == null) throw new ArgumentNullException("collection");
      if (!collection.Any()) 
        return query.Where(t => false);
    
      ParameterExpression p = selector.Parameters.Single();
    
      IEnumerable equals = collection.Select(value =>
         (Expression)Expression.Equal(selector.Body,
              Expression.Constant(value, typeof(TValue))));
    
      Expression body = equals.Aggregate((accumulate, equal) =>
          Expression.Or(accumulate, equal));
    
      return query.Where(Expression.Lambda>(body, p));
    }
    
    //Optional - to allow static collection:
    public static IQueryable WhereIn
      (
        this ObjectQuery query,
        Expression> selector,
        params TValue[] collection
      )
    {
      return WhereIn(query, selector, (IEnumerable)collection);
    }
    

    USAGE:

    public static void Main()
    {
      using (MyObjectContext context = new MyObjectContext())
      {
        //Using method 1 - collection provided as collection
        var contacts1 =
          context.Contacts.WhereIn(c => c.Name, GetContactNames());
    
        //Using method 2 - collection provided statically
        var contacts2 = context.Contacts.WhereIn(c => c.Name,
          "Contact1",
          "Contact2",
          "Contact3",
          "Contact4"
          );
      }
    }
    

提交回复
热议问题