Conditional WHERE clause on an Entity Framework context

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-13 18:13:42

问题


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:


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:


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


来源:https://stackoverflow.com/questions/50841429/conditional-where-clause-on-an-entity-framework-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!