我有一个ASPX页面,它从用户收集5个可选搜索条件,并在网格中返回结果。收集条件并单击视图按钮后,后面的代码会生成过滤器,如下面的
// aSearchCriteria is a class that holds the criteria
...
string filter = string.Empty;
if (!string.IsNullOrEmpty(aSearchCriteria.RegistrationNumber)) filter =
"f.BusinessRegistrationNumber = '" +
aSearchCriteria.BusinessRegistrationNumber + "'";
if (aSearchCriteria.ChangedStartDate != null && aSearchCriteria.ChangedEndDate != null)
{
if (!string.IsNullOrEmpty(filter))
{
filter += " && f.ChangedDate >= '" +
aSearchCriteria.ChangedStartDate.ToShortDateString() +
"' && f.ChangedDate <= '" +
aSearchCriteria.ChangedEndDate.ToShortDateString() + "'";
}
else
{
...
}
}
...
Using (CustomerEntities db = new CustomerEntities())
{
if (!string.IsNullOrEmpty(filter))
{
filter = "f => " + filter;
**return db.Customers.Where(filter).ToList();**
}
else
...
}
...
样品:
"filter" value: f => f.ChangedDate > '01/01/2012' && f.ChangedDate < '14/01/2012'
无论何时执行此操作,我都会收到以下错误消息:
查询语法无效。近期'&gt;',第6行,第5栏。
答案 0 :(得分:1)
您不希望将过滤器设为字符串。你应该做的是将过滤应用到你得到的IQueryable。类似的东西:
var customers = db.Customers.AsQueryable();
if (aSearchCriteria.ChangedStartDate != null && aSearchCriteria.ChangedEndDate != null)
{
customers = customers
.Where(c => c.ChangedDate >= aSearchCriteria.ChangedStartDate &&
c.ChangedDate >= aSearchCriteria.ChangedEndDate);
}
// ... apply other filters as necessary
return customers.ToList();
答案 1 :(得分:0)
假设您正在使用ObjectQuery.Where(字符串) 字符串谓词应该看起来像
"it.ChangedDate > '01/01/2012' && it.ChangedDate < '14/01/2012'"
(没有f =&gt;而且表的别名是它)
请确认它有帮助:)