【问题标题】:Alternative methods/functions in LINQ while converting from SQL to Linq从 SQL 转换为 Linq 时 LINQ 中的替代方法/函数
【发布时间】:2018-07-16 20:27:20
【问题描述】:

您好,我是 Linq 的新手。我需要将以下查询转换为 Linq 并且非常困难。花了将近3个小时仍然无法弄清楚。 Linq 中缺少 Sql 中的大多数函数/方法,例如 Distinct、Not in 等。即使它们可用,我也无法弄清楚如何使用它们。 Linq 中是否有我应该使用的具有不同名称的替代方法/函数,或者它们在 Linq 中甚至不存在,我需要使用不同的方法?如果有人可以帮助我将以下查询转换为 Linq,我将非常有帮助。

SQL 查询

Select count(distinct(UserID))  from dbo.DeansStudents 
             inner join dbo.UserBarSession on DeansStudents.UserBarSessionID = UserBarSession.ID
             inner join dbo.Users on users.ID = UserBarSession.UserID                 
             where UserBarSessionID not in (


             Select b.ID from dbo.DeansStudents,dbo.Users
             left join dbo.Answers on answers.Student=users.ID
             left join dbo.UserBarSession b on Answers.Student = b.UserID
             where AnswerDate between b.StartDate and b.EndDate 
             and AnswerDate between 7/10/2011 and 3/12/2018
             and UserBarSessionID = b.ID and DeanID= 12296 group by Answers.Student,users.FirstName,users.LastName,b.ID) and DeanID =12296

查询已转换为 LINQ

从我过去几天使用 LINQ 开始,我设法将 Sql 查询的第一部分转换为 LINQ。我无法继续第二部分。从“选择 b.id.......”

 var query = from deansStudent in dbo.DeansStudents
             join userBarSession in dbo.UserBarSession
             on deansStudent.UserBarSessionId equals userBarSession.Id
             join users in dbo.Users
             on userBarSession.UserId equals users.Id 

               //Need continuation from here

【问题讨论】:

  • 要回答这个问题,我们需要您的数据模型。您的 SQL 本身似乎有问题,并且无法推断模型。
  • 是的,我明白这一点。它有 18 年历史的应用程序,甚至不知道是谁写了这个 sql 查询。无论如何感谢您的回复。在跳转到 linq 之前,会想办法先重写 sql。
  • 好的。提示:使用精心设计的数据库,您很少需要使用“join”关键字。相反,您在“导航属性”中使用“点符号”。帮自己一个忙,下载 LinqPad。如果您的数据库设计良好,它将显示导航属性。
  • @CetinBasoz 这就是我在我现在正在改造的当前应用程序中使用的东西。主要是 lambda 或 o 数据表示法。因为我不熟悉编写 linq 并将其转换回 lambda,就像我在之前的查询中所做的那样。但这似乎是一件困难的事情

标签: c# sql linq


【解决方案1】:

Linq 中缺少 Sql 中的大部分函数/方法,例如 Distinct、Not in 等

Distinct() 是 Linq 的一部分,NOT IN 可以通过 Except() Linq 扩展方法来实现。

有了这个答案,您应该能够完成您的查询。

【讨论】:

  • 这听起来像是评论,而不是答案。
  • @CetinBasoz 他的问题是如何将 SQL 查询转换为 Linq 查询,因为 Linq 缺少 SQL 运算符的一些等效项。我将文档链接到 Linq 方法,这将允许他做他想要完成的事情。这怎么不能回答他的问题?我不会为他写代码。
  • 我不是对您的“评论”投反对票的人。我认为这仍然是一个评论,并且离 OP 问题的答案还很远。
  • @LewsTherin 感谢您的链接。我确实看到了那里的方法。会经历的。
猜你喜欢
  • 2012-04-10
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多