I have the following EF linq query to get all the employess or specific employee, in case if empId has value.
But the EF is not generating the expected query and it ignores OR condition always
from employee
where employee.DepartmentId == depId && ((employee.Id == empId) || (employee.Id == null))
.ToList()
Expected Query
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id=@empId OR Id IS NULL)
Generated Query by EF when value is passed
SELECT * FROM Employee
WHERE DepartmentId = @DepId AND (Id=@empId)
Generated Query by EF when value is null
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
How to write linq for this Id=@empId OR Id IS NULL ?
NULL(which is impossible according to what you say in yourNote). So what you actually want? I guess you want to bypass the check when the value isnullbut that is something else than what your sql query does.Employeetable would have any rows whereIdisnull. Isn't this the primary key for that table? If not, you may want to consider renaming it.public int Id {get; set; }, that's why EF generate that query(Column=@value OR Column IS NULL). I tried with EF for same and didnt work for me