简体   繁体   中英

Select Multi fields in Entity framework in c#

I want to select 2 or more fields like this: for example we have a list of some people and now they say find people who is male and live in New York
we have 2 fields in here "City" and "Sexual".

I can do it like this

private List<tblTest> GetAll(string city, string sexual)
{
    var all = (from x in db.tblTest
               where x.city == city && x.sexual == sexual
               select x).ToList();
    return all;
}

and this one is not helping:

private List<tblTest> GetAll(string city, string sexual)
{
    var all = (from x in db.tblTest
               where x.city == city || x.sexual == sexual
               select x).ToList();
    return all;
}

with " && " I can do it but if I want to just select " City " it is not working, and I want to search like this for 14 fields and we want to search for some fields not all fields we have and we don't know which fields we want to search

What should I do?

The way I do is following:

private List<tblTest> GetAll(string city, string sexual)
{
    var query = db.tblTest.AsQueryable();
    if(!string.IsNullOrEmpty(city))
    {
        query = query.Where(x => x.city == city);
    }
    if(!string.IsNullOrEmpty(sexual ))
    {
        query = query.Where(x => x.sexual == sexual );
    }
    return all.ToList();
}

It is important to call AsQueryable otherwise it might be that, if you write IEnumerable<tblTest> query = ... , the result is queried more that 1 times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM