我在ASP MVC
中创建了一个actionresult,它应该显示与我的Linq
查询匹配的记录。它正常工作,直到我添加:
records.State == '0' &&
此查询(在t-sql中)在SQL管理工作室中返回正确的结果,但不与Linq一起返回:
public ActionResult Index(string q)
{
viewModel.Records = from records in db.records
where records.State == '0' &&
records.Title.Contains(q)
|| records.Title.Contains(q)
||records.Project.Contains(q)
|| records.Owner.Contains(q)
|| records.Number.Contains(q)
select events;
}
答案 0 :(得分:5)
小心你的逻辑。如果你想要的是
records.State == '0' && [whatever previous logic you have]
您应该将所有先前的逻辑放在括号中:
viewModel.Records = from records in db.records
where records.State == '0' &&
(records.Title.Contains(q)
|| records.Project.Contains(q)
|| records.Owner.Contains(q)
|| records.Number.Contains(q))
select events;
另请注意,您有重复的条件records.Title.Contains(q)
,我会在解决方案中将其删除。
此外,如果您的records.State
是数字类型(例如int
,而不是char/string
),那么您不应该使用撇号,但应该直接使用该数字:
viewModel.Records = from records in db.records
where records.State == 0 &&
(records.Title.Contains(q)
|| records.Project.Contains(q)
|| records.Owner.Contains(q)
|| records.Number.Contains(q))
select events;
答案 1 :(得分:2)
请尝试以下
public ActionResult Index(string q)
{
viewModel.Records = from records in db.records
where records.State == 0 &&
( records.Title.Contains(q)
|| records.Title.Contains(q)
||records.Project.Contains(q)
|| records.Owner.Contains(q)
|| records.Number.Contains(q))
select events;
}
答案 2 :(得分:2)
如果State
属性属于char
类型,您的代码将 ,因为'0'
是char
如果State
的类型为int
/ tinyint
(字节),则应执行此操作
where records.State == 0
&& records.Title.Contains(q)
答案 3 :(得分:2)
您的Contains()
来电看起来是正确的(尽管您有两次Title.Contains()
),但您提到您的State
属性是tinyint
,因此您需要将其比较为这样的(而不是你以前的字符串):
public ActionResult Index(string q)
{
viewModel.Records = from records in db.records
where records.State == 0 && (records.Title.Contains(q)
||records.Project.Contains(q)
|| records.Owner.Contains(q)
|| records.Number.Contains(q))
select events;
}