-7

I need to add where clauses to my query if the user provides input for those values. So far I am trying to use the follow, but the where clause is ignored. By that I mean that only student with the last name starting with Lewis should be returned, but I am not getting that as a result.

            var query = db.STUDENT
            .Where(x => x.STUDENT_CHANGE_IND == null);

        if (!string.IsNullOrEmpty(lastName)) query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));
        if (!string.IsNullOrEmpty(firstName)) query.Where(x => x.STUDENT_FIRST_NAME.StartsWith(firstName));
        if (!string.IsNullOrEmpty(spridenId)) query.Where(x => x.STUDENT_ID.Contains(spridenId));

        var y = query.Take(10).ToList();

The results I get are:

Student ID LastName

002 GUAR - HEMAR    
021 GUAR - Citibank SLC 
08092017    DO NOT USE 92 number mess up    
099 GUAR - ChaseJPM 
161 GUAR - WELLSG   
191 GUAR - TERI 
Cindy Conway
  • 1,814
  • 3
  • 18
  • 19

2 Answers2

7

You need to say

query = query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));

instead of just

query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));
Dennis_E
  • 8,751
  • 23
  • 29
2

Where clauses don't stack if they are called in separate operations. You will need to save the new results each time a Where() statement is executed to ensure that you are working with the filtered list.

Your updated logic would look like this:

var query = db.STUDENT.Where(x => x.STUDENT_CHANGE_IND == null);

if (!string.IsNullOrEmpty(lastName))
{
    query = query.Where(x => x.STUDENT_LAST_NAME.StartsWith("Lewis"));
}
if (!string.IsNullOrEmpty(firstName))
{
    query = query.Where(x => x.STUDENT_FIRST_NAME.StartsWith(firstName));
}
if (!string.IsNullOrEmpty(spridenId))
{
    query = query.Where(x => x.STUDENT_ID.Contains(spridenId));
}

var y = query.Take(10).ToList();
Matt Hensley
  • 908
  • 8
  • 18