LINQ搜索查询不起作用

时间:2015-06-14 13:09:12

标签: c# asp.net asp.net-mvc linq entity-framework

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

即使我动态传递了几个参数,我也需要让它工作

2 个答案:

答案 0 :(得分:3)

您到处使用AND(&&),因此如果这些条件中至少有一个为false,则您的where条件将为false。请尝试使用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

答案 1 :(得分: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))