How to support Contains in Entity Framework 3.5

How can you retrieve the products that are contained in a list of id’s ?

var ids = new List<int>() { 1, 2, 3, 500 };
using (var context = new AdventureWorksEntities())
{
  var products = from product in context.Products
                           where ids.Contains(product.ProductID)
                           select product;
  WriteProducts(products);
}

The good news, this is supported in Entity Framework v4.0, but since I’m on 3.5 I needed to find another solution. Luckily using the info from my previous post I can write an expression for this:

var ids = new List<int>() { 1, 2, 3, 500 };
using (var context = new AdventureWorksEntities())
{
  Expression<Func<Product, bool>> idMatching = null; 
  foreach (var id in ids)
  {
    int productId = id;
    if(idMatching == null)
    {
      idMatching = x => x.ProductID == productId;
    }
    else
    {
      idMatching = idMatching.Or(x => x.ProductID == productId);
    }
  }
  var products = context.Products.Where(idMatching);
  WriteProducts(products);
}

3 Replies to “How to support Contains in Entity Framework 3.5”

  1. And how it works?
    Expression.Or() returns BinaryExpression
    How you convert BinaryExpression to Expression<Func>?

  2. I link to another blog post of mine where there’s an explanation on how to combine expressions with “And” and “Or”. In it there’s also a link to another post having all the necessary code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.