Linq多條件關聯查詢

在使用Linq今天多表關聯查詢時關聯表查詢還算是比較複雜的,今天遇到一個關聯表查詢而且還是多條件不定項查詢,查詢條件可有可無,要進行linq查詢,一開始也是沒思路,網上百度了好多,終於找到解決方法,在where中使用三則運算來判斷查詢條件是否存在。

            entities =  from e in entities join h in houses on e.HouseId equals h.Id
                         join v in villages on h.VillageId equals v.Id
                         where (search.CompanyId == 0 ? true : v.CompanyId == search.CompanyId)
                         && (string.IsNullOrWhiteSpace(search.KeyWord.Trim()) ? true : (v.Name.Contains(search.KeyWord) || v.CounName.Contains(search.KeyWord) || v.CityName.Contains(search.KeyWord))) 
                         && (string.IsNullOrWhiteSpace(search.CityCode) ? true : v.CityCode == search.CityCode) 
                         && (string.IsNullOrWhiteSpace(search.CounCode) ? true : v.CounCode == search.CounCode) 
                         && (search.CompanyId == 0 ? true : h.CompanyId == search.CompanyId) 
                         && (search.RoomCount == 0 ? true : h.RoomCount == search.RoomCount) 
                         && (search.CompanyId == 0 ? true : e.CompanyId == search.CompanyId) 
                         && (search.RentMaxMoney.HasValue && search.RentMaxMoney.Value > 0 ? e.RentMoney <= search.RentMaxMoney.Value : true) 
                         && (search.RentMinMoney.HasValue && search.RentMinMoney.Value > 0 ? e.RentMoney >= search.RentMinMoney.Value : true) 
                         && (search.RentType.HasValue ? e.RentType == search.RentType.Value:true) 
                         && e.IsOnShelf
                         select e;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章