Daniel Gustafsson
Daniel Gustafsson

Reputation: 1817

Query value if it is not zero using Entity Framework

Using EF, I want to query an integer, but if the value is 0, I don't want to do the query.

rentalContext.Apartments
    .Include(a => a.ApartmentType)
    .Include(a => a.Files)
    .Include(a => a.Address)
    .Where(a => some other search conditions &&
        (filters.CityId != 0 && a.Address.CityObject.Id == filters.CityId))
    .ToList()
    .OrderByDescending(a => a.Created);

It works fine if CityId isn't 0, but if it is zero, then it returns 0 objects in the list. Is this not the way you are supposed to do this?

Upvotes: 0

Views: 172

Answers (1)

adiga
adiga

Reputation: 35222

Now it will check the second condition only if filters.CityId == 0 is false.

rentalContext.Apartments
    .Include(a => a.ApartmentType)
    .Include(a => a.Files)
    .Include(a => a.Address)
    .Where(a => some other search conditions &&
         (filters.CityId == 0 || a.Address.CityObject.Id == filters.CityId))
    .OrderByDescending(a => a.Created)
    .ToList();

Upvotes: 1

Related Questions