【发布时间】:2017-01-21 03:34:16
【问题描述】:
嗨,伙计们,我使用动态 SQL 进行搜索查询,我曾经在其中逐个附加 WHERE 和 AND 子句并形成一个语句,我最近来到下面的替代品,生活真是太棒了
cool alternates of Dynamic WHERE-Clause
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);
}
table 有类似的值
id Bathroom Floors
1 1 2
2 1 4
3 2 6
4 3 1
我需要 id 为 1 和 2 的结果 例如在前端用户只想用“1”填充浴室字段并将地板字段留空
【问题讨论】:
-
@AntoinePelletier 区别在于 && 和 II
-
并不完全一样。在您的查询中,您的
coalesce位于参数上,如果记录值为空,则将其作为默认值。在您的 c# lambda 中,您正在检查参数是否与表值相同,然后检查表值是否为null,但这忽略了参数中包含空值的可能性。 -
@Igor 我将 coalesce 转换为 c# 代码是一个蹩脚的尝试,我只需要 C# 中的类似 coalesce 的功能
-
您应该从表达式主体中删除这些空检查。动态构建表达式:stackoverflow.com/a/14622200/861716
-
特别是。对于
||替代方案,您必须按照我上面提到的方法进行操作。请注意,即使只有一个= null条件为真,它也总是返回所有行。
标签: c# entity-framework linq tsql