2012-01-27 24 views
40

我必須列出所有要分配給「僱員」的「班次」數據,但如果班次數據已存在於員工數據中,則不得包含班次數據。讓我們看看圖像樣本。如何選擇哪裏不存在使用LINQ?

No filtering yet

這個查詢解決了這個問題。我發現這個在這裏:
Scott's Blog

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

讓我們看到的結果是:

Filtered

現在的問題是,我怎麼可能讓這個在LINQ?我正在使用實體框架。
希望有人能幫助。非常感謝!!!

+1

你可以簡單地做一個加入...如果有合適的記錄不存在,左記錄應不包括 – 2012-01-27 09:09:10

+0

@AndreasNiedermair你能舉一些例子嗎?我做了很多加入,但我沒有得到正確的。 – fiberOptics 2012-01-27 09:11:41

+0

可能重複的[LINQ - Where exists](http://stackoverflow.com/questions/899090/linq-where-not-exists) – 2012-01-27 09:16:41

回答

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

希望這有助於

+0

哎呀,是的,固定的,謝謝@RuneFS – 2012-01-27 09:20:58

+0

「&& es.empid = 57」必須在「(es.shiftid == s.shiftid)」中。它工作但它不會返回完整的數據,有些數據丟失。 – fiberOptics 2012-01-27 09:37:46

21

結果SQL會有所不同,但結果應該是一樣的:

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

您應該始終使用'Any()'而不是'Count()'來確定是否存在_are_結果... – Nuffin 2012-01-27 09:14:42

+4

您應該使用!.Any()而不是count。如果沒有,性能將會是相同的,但是在所有情況下,如果超過1個元素,任何元素的速度都會更快,因爲在找到第一個元素之後停止迭代。 – 2012-01-27 09:15:40

+0

足夠公平,已編輯。 – hyp 2012-01-27 09:26:50

0

如何..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s) 

編輯:這將在有相關僱員轉移的情況下(因爲加入),給你轉移。對於「不存在」我會做什麼@ArsenMkrt或@hyp建議

+0

你失去了empid = 57檢查 – 2012-01-27 09:19:09

+0

是的,加上我意識到我不是在有效地回答正確的問題! – 2012-01-27 09:21:02

+0

是的,因爲結果應該是結果集,你越來越bool值 – 2012-01-27 09:22:26

2

首先,我建議修改了一下你的SQL查詢:

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

該詢問提供相同的功能。 如果你想獲得與LINQ相同的結果,你可以試試這個代碼:

//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(); 
+0

你sql查詢工作完美。但在linq中,我對單個查詢很好。謝謝! – fiberOptics 2012-01-27 09:45:56

-1
 Dim result2 = From s In mySession.Query(Of CSucursal)() 
         Where (From c In mySession.Query(Of CCiudad)() 
          From cs In mySession.Query(Of CCiudadSucursal)() 
          Where cs.id_ciudad Is c 
          Where cs.id_sucursal Is s 
          Where c.id = IdCiudad 
          Where s.accion <> "E" AndAlso s.accion <> Nothing 
          Where cs.accion <> "E" AndAlso cs.accion <> Nothing 
          Select c.descripcion).Single() Is Nothing 
         Where s.accion <> "E" AndAlso s.accion <> Nothing 
         Select s.id, s.Descripcion 
+1

請說明您使用此代碼所做的事情。 – 2017-07-15 23:19:52