Conditional WHERE clause on an Entity Framework context

entity-framework entity-framework-core

Question

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.

1
1
6/13/2018 3:51:56 PM

Accepted Answer

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();
2
6/13/2018 5:34:56 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow