Spaceman
Spaceman

Reputation: 37

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?

Upvotes: 0

Views: 155

Answers (1)

Michael Mairegger
Michael Mairegger

Reputation: 7301

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.

Upvotes: 2

Related Questions