2012-01-27 4 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); 

をの結果を見てみましょう:今、私の質問は、私はLINQのでこれを作ることができるか、である

Filtered

を?私はエンティティフレームワークを使用しています。
誰かが助けてくれることを願っています。どうもありがとう!!!

+1

あなたは、単に参加しない可能性が...右レコードが存在しない場合は、左のレコードがすべき –

+0

@AndreasNiedermairあなたはいくつかの例を挙げることができますか?私はたくさんの参加をしましたが、私は正しいものを手に入れませんでした。 – fiberOptics

+0

[LINQの存在する可能性はありません](http://stackoverflow.com/questions/899090/linq-where-not-exists) –

答えて

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

ホープこれは

+0

oops、yea、fixed、thanks @RuneFS –

+0

"&& es.empid = 57"は "(es.shiftid == s.shiftid)"内にある必要があります。それは動作しますが、完全なデータを返しません、いくつかのデータがありません。 – fiberOptics

21

結果のSQLは異なるものになりますが、結果は同じでなければなりません:この意志:

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

結果が存在するかどうかを判断するには、 'Count()'の代わりに常に 'Any()'を使うべきです... – Nuffin

+4

カウントの代わりに.Any()を使用してください。存在しない場合は、同じパフォーマンスが得られますが、1つ以上の要素がある場合は、最初の要素が見つかった後に反復を停止するので、より速くなります。 –

+0

十分に編集されています。 – hyp

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にしてください、またはすべての

+0

あなたはempid = 57チェックを失います –

+0

うん、プラス私は正しい質問にactaully答えていないよ! –

+0

確かに、結果が結果セットになるはずだから、ブール値 –

2

ファーストを示唆@hypために、私は少しあなたの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

-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

このコードで何をしているのかを明確にしてください。 –

関連する問題