简体   繁体   中英

LINQ search query doesn't work

I'm trying to write a search query in LINQ. Below is the where condition.

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

It doesn't return any values if I pass a single parameter. For example if I pass 'Chamara' as fullname it doesn't return any result but if I pass all the parameters at the once then it returns the matching records.

I need to get this to work even when I pass several parameters dynamically

You are using AND ( && ) everywhere, so if at least one of these conditions is false, your where condition will be false. Try using OR conditions instead:

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

In this case in any of these conditions if you have empty parameter, only the first part of condition will be evaluated, otherwise the second condition will be evaluated.

One potential issue is that Entity Framework might not be able to translate this to actual SQL. In this case, you can use such approach:

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

What you're asking is semi-confusing but i think you want to search for every string if exists, which translates to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM