2015-06-14 214 views
-1

我正试图在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'作为全名传递,它不会返回任何结果,但如果我传递一次所有参数,则会返回匹配的记录。

我需要当我通过几个参数动态

+0

什么应该是结果,如果你不通过任何东西? (我的意思是,所有字符串都是空或空)? – Steve

回答

3

您正在使用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 
+0

我在想同样的事情,但是我的头脑混杂着所有这些情况! :) – AmmarCSE

+0

EF可以翻译。但第二种方法更好的可读性 –

+0

在这里的OP请求中,有些事情不太正确。如果所有字符串都为空或空值,结果应该是什么? – Steve

0

什么你问的是半混乱,但我认为你要搜索的每一个是否存在串,转化为

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))