2017-09-10 80 views
0

使用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對象。這不是你應該這樣做的方式嗎?

+0

'filters.CityId!= 0 &&'should be'filters.CityId == 0 || ([德摩根法]](https://en.wikipedia.org/wiki/De_Morgan%27s_laws)) –

回答

1

現在只有在filters.CityId == 0爲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(); 
+0

nope也沒有工作:( –

+0

@DanielGustafsson更新了答案,我誤解了你的意思 – adiga