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); } |
And how it works?
Expression.Or() returns BinaryExpression
How you convert BinaryExpression to Expression<Func>?
using System.Linq;
using System.Linq.Expressions;
“Expression.Or()” is not recognized, why?
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.