如果使用Entity Framework不是零,则查询值

时间:2017-09-10 09:06:43

标签: entity-framework linq

使用EF,我想查询整数,但如果值为0,我不想进行查询。

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

如果CityId不是0,它可以正常工作,但如果它为零,则返回列表中的0个对象。这不是你应该这样做的方式吗?

1 个答案:

答案 0 :(得分:1)

现在只有当filters.CityId == 0为假时才会检查第二个条件。

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