我已经查看了一些关于 SO 的问题并尝试了谷歌,但无法让它发挥作用。我有一个搜索页面,用户可以在其中输入和选择下拉列表,其中填写了 0 到 10 个字段。(可以返回“所有”结果)。在我有一个允许多项选择的字段之前,它运行良好
<select name="area" size="25" multiple="multiple">
<option>foo</option>
<option>bar</option>
<option>baz</option>
<!--blah blah blah-->
</select>
<input name="someField"/>
我无法将其转换为 EF lambda 语句。想象一下,用户选择foo
并baz
输入42
到someField
框中。搜索应该返回area
具有其中之一的结果,并且具有正确的值someField
。
//...
var entities = db.entities;
//... this is inside of a switch/loop through the forms collection
string value = Request.Form[key];
//...
If (area <> "") {
string[] areaSplit = value.Split(',');
foreach (string s in subSplit)
{
string temp = s;
entities.Where(x => x.area.Contains(temp)); //1
}
}
//...
entities.Where(x => x.someField == value);
所以 where //1
is where 不应该是排他的。换句话说entities.area
,可以具有来自表单字段的任何值之一area
。在 SQL 查询中,我可能会写
... someField = 42 and (area = 'foo' or area = 'baz')
只写一个 SQL 查询会更好(高效,最佳实践)吗?
使用谓词构建器进行编辑
var outer = PredicateBuilder.True<entity>();
var inner = PredicateBuilder.False<entity>();
//... this is inside of a switch/loop through the forms collection
string value = Request.Form[key];
//...
string[] areaSplit = value.Split(',');
foreach (string s in subSplit)
{
string temp = s;
inner = inner.Or(x => x.area.Contains(temp)); //1
}
//..
outer = outer.And(x => x.someField == value);
//...end of loop
outer.And(inner.Expand());
var foo = db.entity.AsExpandable().Where(outer.Expand());
但是似乎它忽略了这一inner
部分。SQL 探查器不显示inner
查询