How to SELECT WHERE NOT EXIST using LINQ?

118,291

Solution 1

from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;

Hope this helps

Solution 2

The outcome sql will be different but the result should be the same:

var shifts = Shifts.Where(s => !EmployeeShifts.Where(es => es.ShiftID == s.ShiftID).Any());

Solution 3

First of all, I suggest to modify a bit your sql query:

 select * from shift 
 where shift.shiftid not in (select employeeshift.shiftid from employeeshift 
                             where employeeshift.empid = 57);

This query provides same functionality. If you want to get the same result with LINQ, you can try this code:

//Variable dc has DataContext type here
//Here we get list of ShiftIDs from employeeshift table
List<int> empShiftIds = dc.employeeshift.Where(p => p.EmpID = 57).Select(s => s.ShiftID).ToList();

//Here we get the list of our shifts
List<shift> shifts = dc.shift.Where(p => !empShiftIds.Contains(p.ShiftId)).ToList();
Share:
118,291
fiberOptics
Author by

fiberOptics

learner

Updated on July 16, 2020

Comments

  • fiberOptics
    fiberOptics almost 4 years

    I have to list all "shift" data to be assigned to an "employee" but shift data must not be included if it is already existing in employee's data. Let's see the image sample.

    No filtering yet

    This query solves the problem. I found this here:
    Scott's Blog

    select * from shift where not exists 
    (select 1 from employeeshift where shift.shiftid = employeeshift.shiftid
    and employeeshift.empid = 57);  
    

    Let's see the result:

    Filtered

    Now my question is, how could I make this in linQ ? I'm using entity framework.
    Hope someone could help. Thanks a lot!!!