【问题标题】:How to SELECT WHERE NOT EXIST using LINQ?如何使用 LINQ 选择 WHERE NOT EXIST?
【发布时间】:2012-01-27 09:07:11
【问题描述】:

我必须列出要分配给“员工”的所有“班次”数据,但如果班次数据已经存在于员工的数据中,则不得包含该数据。让我们看一下图像示例。

这个查询解决了这个问题。我在这里找到了这个:
Scott's Blog

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

让我们看看结果:

现在我的问题是,我怎样才能在 linQ 中做到这一点?我正在使用实体框架。
希望有人能帮忙。非常感谢!!!

【问题讨论】:

标签: c# sql linq entity-framework


【解决方案1】:
from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;

希望对你有帮助

【讨论】:

  • "&&es.empid=57" 必须在 "(es.shiftid==s.shiftid)" 内。它工作,但它不返回完整的数据,一些数据丢失。
【解决方案2】:

结果sql会不同,但结果应该是一样的:

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

【讨论】:

  • 您应该始终使用Any() 而不是Count() 来确定是否有结果...
  • 你应该使用 !.Any() 而不是 count。如果没有,性能将是相同的,但在所有超过 1 个元素的情况下,任何一个都会更快,因为它会在找到第一个元素后停止迭代
  • 你丢失了 empid = 57 条件?
【解决方案3】:

首先,我建议修改一下你的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();

【讨论】:

  • 您的 sql 查询工作完美。但是在 linq 中,我对单个查询很好。谢谢!
【解决方案4】:

怎么样..

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 建议的事情

【讨论】:

  • 是的,而且我意识到我并没有真正回答正确的问题!
  • 是的,因为结果应该是结果集,所以你得到的是布尔值
【解决方案5】:
        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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多