我正在尝试使用其他搜索条件扩展我的linq查询,以便通过向函数发送List<Listitem>
来过滤数据以进行处理。列表可以包含一个或多个项目,目标是检索符合任何条件的所有项目。
由于我正在向函数发送多个搜索条件,因此目标是使得更准确的过滤结果,我发送给过滤器的信息越多。如果一个或多个标准为空,则过滤器将得到不太准确的结果。
每次执行以下代码时都会引发异常,我无法弄清楚如何解决using语句以包含List<ListItem>
。提前感谢所有帮助!
例外:Unable to create a constant value of type 'System.Web.UI.WebControls.ListItem'. Only primitive types or enumeration types are supported in this context.
using (var db = new DL.ENTS())
{
List<DL.PRODUCTS> products =
(from a in db.PRODUCTS
where (description == null || description == "" ||
a.DESCRIPTION.Contains(description)) &&
(active == null || active == "" || a.ACTIVE.Equals(active, StringComparison.CurrentCultureIgnoreCase)) &&
(mID == null || mID == "" || a.MEDIA_ID == mID) &&
(mID == null || objTypes.Any(s => s.Value == a.OBJECTS)) //Exception here!
select a).ToList<DL.PRODUCTS>();
return products;
}
答案 0 :(得分:4)
将原始值集合传递给表达式:
using (var db = new DL.ENTS())
{
var values = objTypes.Select(s => s.Value).ToArray();
List<DL.PRODUCTS> products =
(from a in db.PRODUCTS
where (description == null || description == "" || a.DESCRIPTION.Contains(description)) &&
(active == null || active == "" || a.ACTIVE.Equals(active, StringComparison.CurrentCultureIgnoreCase)) &&
(mID == null || mID == "" || a.MEDIA_ID == mID) &&
(mID == null || values.Contains(a.OBJECTS))
select a).ToList<DL.PRODUCTS>();
return products;
}
这将生成SQL IN子句。
注意 - 您可以使用lambda语法通过基于某些条件添加过滤器来撰写查询:
var products = db.PRODUCTS;
if (!String.IsNullOrEmpty(description))
products = products.Where(p => p.DESCRIPTION.Contains(description));
if (!String.IsNullOrEmpty(active))
products = products.Where(p => p.ACTIVE.Equals(active, StringComparison.CurrentCultureIgnoreCase)));
if (!String.IsNullOrEmpty(mID))
products = products.Where(p => p.MEDIA_ID == mID);
if (mID != null)
products = products.Where(p => values.Contains(p.OBJECTS));
return products.ToList();
答案 1 :(得分:1)
Linq无法将ListItem
上的谓词转换为对Sql有用的内容。
我建议您先将ListItems
的值预先投影到一个简单的List<string>
中,然后再将其与Contains(转换为IN)一起使用
var listValues = objTypes.Select(_ => _.Value).ToList();
List<DL.PRODUCTS> products = ...
listValues.Contains(a.OBJECTS))