c# - LINQ search query doesn't work -
i'm trying write search query in linq. below 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 values if pass single parameter. example if pass 'chamara' fullname doesn't return result if pass parameters @ once returns matching records.
i need work when pass several parameters dynamically
you using , (&&
) everywhere, if @ least 1 of these conditions false, where
condition 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 case in of these conditions if have empty parameter, first part of condition evaluated, otherwise second condition evaluated.
one potential issue entity framework might not able translate actual sql. in case, can use such approach:
var query = // original query without condition // check if condition valid , add condition if(!string.isnullorempty(namewithinitials)) { query = query.where(tb => tb.namewithinitials.contains(namewithinitials)); } // repeat other conditions
Comments
Post a Comment