我有以下 EF linq 查询来获取所有雇员或特定员工,以防 empId 有值(value)。
但是 EF 没有生成预期的查询,它总是忽略 OR
条件
from employee
where employee.DepartmentId == depId && ((employee.Id == empId) || (employee.Id == null))
.ToList()
预期查询
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id=@empId OR Id IS NULL)
传递值时由 EF 生成查询
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id=@empId)
当值为 null 时由 EF 生成查询
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id IS NULL)
Note: No Employee record has Id value NULL and it returns 0 instead of all employees
如何为此 Id=@empId OR Id IS NULL
编写 linq?
最佳答案
你说这是你预期的查询:
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id=@empId OR Id IS NULL)
但我很确定它不是,因为 Id
永远不会为 null(您在 Note 中也说过),因为它是那张 table 你实际上是指这个查询:
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id=@empId OR @empId IS NULL)
因此如果参数为NULL
,您希望绕过检查并返回所有记录。请注意,这不是性能方面的最佳方式。当您不想按 Id
过滤时,您应该使用不带过滤器的查询。恐怕这不会产生最有效的查询计划。我会用这个:
IQueryable<Employee> allDepartmentEmployees =
from employee in ...
where employee.DepartmentId == depId;
select employee;
if(empId.HasValue) // presuming it's a nullable type
{
allDepartmentEmployees = allDepartmentEmployees.Where(e => e.Id == empId.Value);
}
List<Employee> employeeList = allDepartmentEmployees.ToList();
所以只有在给定参数的情况下才进行过滤。那么这只会返回一条记录。
关于c# - 具有值或 null 的 Entity Framework LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48300140/