将SQL转换为Linq,其中有in子句

时间:2012-06-28 21:42:38

标签: sql vb.net linq linq-to-sql sql-to-linq-conversion

我想知道如何将下面列出的SQL查询转换为VB中的LINQ查询。

SELECT FacilityID 
FROM tblFacilityProjects 
WHERE FreedomEnabled = True and ProjectID in (840,841,842)

3 个答案:

答案 0 :(得分:4)

我认为应该这样做:

Dim projectIds = New Integer() {840, 841, 842}
Dim result = From proj In db.tblFacilityProjects _
             Where proj.FreedomEnabled = True AndAlso _
                   projectIds.Contains(proj.ProjectID) _
             Select FacilityID

答案 1 :(得分:0)

在SQL中查询

SELECT [Id], [UserId]
FROM [Tablename]
WHERE [UserId] IN (2, 3)

在LINQ中查询

使用VB的Contains功能。

Dim coll As Integer() = {2, 3}
Dim user = From u In tablename Where coll.Contains(u.UserId.Value) New 
From {
    u.id, u.userid
}

http://www.c-sharpcorner.com/blogs/4479/sql-in-and-not-in-clause-in-linq-using-vb-net.aspx

答案 2 :(得分:0)

创建项目ID列表

Dim list As New List(Of Integer)
list.Add(840)
list.Add(841)
list.Add(842)

现在你必须在LINQ中使用它。

dim facilityId = from fp in tblFacilityProjects 
                 where FreedomEnabled == true
                 where list.Contains(ProjectID)
                 select new
                 {
                   FacilityID=fp.FacilityID
                 }

您可能需要对VB.net进行一些调整。