[英]Entity Framework Search functionality with Dynamic SQL WHERE clause
嗨,大家好,我使用Dynamic SQL進行搜索查詢,我曾經將WHERE
& AND
子句逐段附加並形成一條語句,為此我最近來到了下面,這真是太棒了
Select * From tblEmployees
where EmployeeName = Coalesce(@EmployeeName, EmployeeName) AND
Department = Coalesce(@Department, Department ) AND
Designation = Coalesce(@Designation, Designation) AND
JoiningDate >= Coalesce(@StartDate, JoiningDate) AND
JoiningDate <= Coalesce(@EndDate, JoiningDate) AND
Salary >= Coalesce(@Salary, Salary)
現在的問題是,因為我實現了實體框架,所以我需要使用Linq查詢實現相同的功能。 我有目前無法處理的可為空的字節類型和可為空的布爾值
就像Coalesce
一樣,我的愚蠢嘗試是&& (s.Floors == deal.Floors.HasValue ? null : s.Floors)
下面的代碼不符合任何結果
[HttpPost]
public ActionResult Results(Deal deal, bool exactMatch)
{
List<Deal> deals;
if (exactMatch)
{
deals = dataBase.Deals.Where(s =>
(s.OwnerName.Contains(deal.OwnerName) || s.OwnerName == null)
&& (s.Rooms == deal.Rooms || s.Rooms == null)
&& (s.BathRooms == deal.BathRooms || s.BathRooms == null)
&& (s.Floors == deal.Floors || s.Floors == null)
&& (s.Builtin == deal.Builtin || s.Builtin == null)
&& (s.Kitchens == deal.Kitchens || s.Kitchens == null)
&& (s.DoubleUnit == deal.DoubleUnit || s.DoubleUnit == null)
&& (s.Corner == deal.Corner || s.Corner == null)
&& (s.Remarks.Contains(deal.Remarks) || s.Remarks == null)
).ToList();
}
else
{
deals = dataBase.Deals.Where(s =>
(s.OwnerName.Contains(deal.OwnerName) || s.OwnerName == null)
|| (s.Rooms == deal.Rooms || s.Rooms == null)
|| (s.BathRooms == deal.BathRooms || s.BathRooms == null)
|| (s.Floors == deal.Floors || s.Floors == null)
|| (s.Builtin == deal.Builtin || s.Builtin == null)
|| (s.Kitchens == deal.Kitchens || s.Kitchens == null)
|| (s.DoubleUnit == deal.DoubleUnit || s.DoubleUnit == null)
|| (s.Corner == deal.Corner || s.Corner == null)
|| (s.Remarks.Contains(deal.Remarks) || s.Remarks == null)
).ToList();
}
return View(deals);
}
表的值如下
id Bathroom Floors
1 1 2
2 1 4
3 2 6
4 3 1
我需要具有ID 1和2的結果,例如在前端用戶中,我只想將浴室字段填充為“ 1”,而將地板字段保留為空
您正在測試表中的字段是否等於'deal'屬性或該字段為空,而不是這樣做:
s.Remarks.Contains(deal.Remarks) || deal.Remarks == null
如果這樣做,它應該是等效的查詢。
您也可以累積執行此操作。 例如,在完全匹配的情況下,您可以執行以下操作:
deals = dataBase.Deals;
if (deal.OwnerName != null)
deals = deals.Where(s => s.OwnerName.Contains(deal.OwnerName));
if (deal.Rooms != null)
deals = deals.Where(s => s.Rooms == deal.Rooms)
這樣可以使查詢結果更加有效。 有一種類似的方法可以通過使用聯合對不完全匹配進行此操作。 我不了解語法。
不太一樣。 在查詢中, coalesce
是在參數上,然后將記錄值作為默認值(如果為空)。 在您的C#lambda中,您正在檢查參數是否與表值相同,然后檢查表值是否為null
但這忽略了參數中具有null值的可能性。
例
SQL
Department = Coalesce(@Department, Department )
將會
(s.Department == deal.Department || deal.Department == null)
這不是你現在擁有的
(s.Department == deal.Department || s.Department == null)
如果您想復制COALESCE
表達式,現在可以用這種方式編寫它,盡管我不確定它是否會降低效率/性能。
(s.Department == (deal.Department ?? s.Department))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.