LINQ搜索查询不起作用
问题描述:
我正试图在LINQ中编写一个搜索查询。以下是哪里的条件。LINQ搜索查询不起作用
where (!string.IsNullOrEmpty(nameWithInitials)
&& tb.NameWithInitials.Contains(nameWithInitials))
&& (!string.IsNullOrEmpty(studentRegNo)
&& tbSR.StudentRegistrationNo.Contains(studentRegNo))
&& (!string.IsNullOrEmpty(NIC) && tb.NIC.Contains(NIC))
&& (!string.IsNullOrEmpty(fullName) && tbi.Name.Contains(fullName))
如果我传递一个参数,它不返回任何值。例如,如果我将'Chamara'作为全名传递,它不会返回任何结果,但如果我传递一次所有参数,则会返回匹配的记录。
我需要当我通过几个参数动态
答
您正在使用AND(&&
)无处不在,所以如果这些条件中的至少一个是假的,你where
条件将是错误的这甚至工作。尝试使用OR条件,而不是:
where (string.IsNullOrEmpty(nameWithInitials) || tb.NameWithInitials.Contains(nameWithInitials))
&& (string.IsNullOrEmpty(studentRegNo) || tbSR.StudentRegistrationNo.Contains(studentRegNo))
&& (string.IsNullOrEmpty(NIC) || tb.NIC.Contains(NIC))
&& (string.IsNullOrEmpty(fullName) || tbi.Name.Contains(fullName))
在这种情况下,任何一个条件,如果你有空参数,只有条件的第一部分将被评估,否则第二个条件进行评估。
一个潜在的问题是实体框架可能无法将其转换为实际的SQL。在这种情况下,你可以使用这样的方法:
var query = // your original query without where condition
// Check if the condition is valid and only then add where condition
if(!string.IsNullOrEmpty(nameWithInitials))
{
query = query.Where(tb => tb.NameWithInitials.Contains(nameWithInitials));
}
// repeat this for all other conditions
答
什么你问的是半混乱,但我认为你要搜索的每一个是否存在串,转化为
where ((string.IsNullOrEmpty(nameWithInitials)
|| tb.NameWithInitials.Contains(nameWithInitials))
&& (string.IsNullOrEmpty(studentRegNo)
|| tbSR.StudentRegistrationNo.Contains(studentRegNo))
&& (string.IsNullOrEmpty(NIC) || tb.NIC.Contains(NIC))
&& (string.IsNullOrEmpty(fullName) || tbi.Name.Contains(fullName))
什么应该是结果,如果你不通过任何东西? (我的意思是,所有字符串都是空或空)? – Steve