【问题标题】:sql to linq, same query but not working?sql to linq,相同的查询但不起作用?
【发布时间】:2018-01-11 10:07:54
【问题描述】:

我的 SQL Server 管理工作室中有这个

      SELECT DISTINCT Hours.id, Hours.hour, Shift.Date, Shift.Doctor
      FROM dbo.Hours, dbo.Shift
      WHERE(Shift.Date= '2017/08/04' AND Shift.Doctor= 530) AND (Hours.Id 
      NOT IN(SELECT Shift.Hour                                                                                            
      FROM dbo.Shift) )

这正是我想要的。

但是当我尝试使用 LINQ 时:

日期是 2017/08/04 id 是 530

 var hoursFree = (from s in db.Shift
                  from h in db.Hours
                  where ((s.Date == date && s.Doctor == id) && !(from s in db.Shift select t.Hours).Contains(h.Id))                                                                                 
                  select h).ToList().Distinct();

LINQ 不应该给我带来完全相同的东西吗?

【问题讨论】:

  • 这取决于dateid 是什么。此外,not in 子句也不一样。
  • 对此不确定,但您在LINQ 中有两次from s in db.Shift!(from s in db.Shift 会是过滤后的数据吗?
  • 只有这些列吗? ID、时间、日期和医生?如果不是,那么您也会在其他字段上调用 ​​distinct。
  • 请描述到底是哪里出了问题。
  • 显示两个数据集的结果会有所帮助。

标签: c# asp.net sql-server entity-framework linq


【解决方案1】:
var hoursFree= (from h in db.Hours
                where !(from s in db.Shift
                where (s.Date == date && s.Doctor == id)
                select s.Hour).Contains(h.Id)                                                                              
                select h).Distinct().ToList();

现在正在运行,谢谢 WEI_DBA

【讨论】:

  • .ToList()之前执行.Distinct()
【解决方案2】:

您的原始查询中有两个问题。

1) 您没有选择相同的值。在 SQL 查询中,您选择了四个字段:Hours.id、Hours.hour、Shift.Date、Shift.Doctor,但在 LINQ 查询中,您只选择了 Hours 表中的字段以及所有字段。相反,您应该使用以下方法选择相同的数据:new { h.Id, h.Hours, s.Date, s.Doctor}

2) 在 ToList() 之后使用 Distinct() 会导致 Distinct() 方法在数据返回到客户端后在本地运行,这可能与在服务器上运行的 DISTINCT 具有不同的行为。您应该以另一种方式订购它们,.Distinct().ToList()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-28
    • 2011-05-26
    • 1970-01-01
    • 2010-09-21
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多