i have table of products , table of categories, can select id of category this:
var result = db.tblproducts.where(p => p.tblcategories.any(c => c.id == 1)); however, want able select based on list of categories:
var catids = new list<int>() { 1,2,3 }; var results = db.tblproducts.where(r => r.tblcategories.any(t => catids.contains(t.id))); i following error:
linq entities not recognize method 'boolean contains(int32)' method, , method cannot translated store expression.
presumably because using contains compare entities local variables. there way this?
try create expression values. f.e.:
static expression makeorexpression<t, p>(expression<func<t, p>> whattocompare, ienumerable<p> values) { expression result = expression.constant(true); foreach (var value in values) { var comparison = expression.equal(whattocompare, expression.constant(value)); result = expression.or(result, comparison); } return result; } how use:
var results = db.tblproducts.where(r => r.tblcategories.any(makeorexpression(t => t.id, catids))); the method makeorexpression create expression t.id == 1 || t.id == 2 || t.id == 3 list { 1, 2, 3 } dynamically, , ef translate sql condition.
Comments
Post a Comment