Dave
Dave

Reputation: 253

Conditional WHERE clause on an Entity Framework context

objRecord = await _context.Persons
    .Where(tbl => tbl.DeletedFlag == false)
    .ToListAsync();

This is the EF code I've got which successfully gets all the records from the Person table where DeletedFlag is false.

I want to add another where criteria that if a surname has been passed in, then add the extra where clause

.Where(tbl => tbl.Surname.Contains(theSurname))

I've tried IQueryable and some other options but can't figure out how to do the equivalent of

string theSurname = "";
objRecord = await _context.Persons
    .Where(tbl => tbl.DeletedFlag == false)
    if ( theSurname != "") {
        .Where(tbl => tbl.Surname.Contains(theSurname))
    }
    .ToListAsync();

which obviously doesn't work as you can't put an if statement in an EF call.

I can add a criteria afterwards that limits objRecord, but I don't want to retrieve all the records, then cut it down, I'd rather only get the records I need.

Upvotes: 4

Views: 1832

Answers (2)

user1810535
user1810535

Reputation: 109

You can combine conditions in the Where method by just adding tbl.Surname.Contains(theSurname) so your final query will look like below:

objRecord = await _context.Persons
                          .Where(tbl => tbl.DeletedFlag == false && 
                                        tbl.Surname.Contains(theSurname))
                          .ToListAsync();

Upvotes: 2

Vivek Nuna
Vivek Nuna

Reputation: 1

You have to apply logical AND (&&) with the existing condition in Where clause i.e. tbl.Surname.Contains(theSurname);

So your query would be

.Where(tbl => tbl.DeletedFlag == false && tbl.Surname.Contains(theSurname));

Upvotes: 1

Related Questions