LinqToSql - 。包含来自包含主键的内存列表中的多列主键

时间:2011-08-23 21:54:55

标签: vb.net linq tsql contains

在客户端上,我有一个匿名列表,其中包含先前从数据库中选择的多列主键。

然后我需要从DB中选择所有与我存储在内存中的主键列表相同的记录。

我认为以下(简化)示例将让您了解我想要存档的内容,您可以看到我已经找到了一种方法,但我希望有人有更好的解决方案? : - )

.NET示例:

Sub findKeys()
    Dim clientLst As New List(Of PriKeys)
    clientLst.Add(New PriKeys With {.p = 1, .i = 2})
    clientLst.Add(New PriKeys With {.p = 3, .i = 1})
    Using DC As New LTSQDataContext
        Dim p_lst = clientLst.Select(Function(x) x.p).ToList
        Dim i_lst = clientLst.Select(Function(x) x.i).ToList
        Dim concLst As New List(Of String) ' used for example 2/3
        clientLst.ForEach(Sub(v) concLst.Add(v.p & "|" & v.i))

        '1:  Wrong - returns row 1,1 (just had to try)
        Dim try1 = (From q In DC.TestTbl1s
                    Where p_lst.Contains(q.p) AndAlso i_lst.Contains(q.i)
                    Select q.p, q.i).ToList

        '2: Works! - but extremely slow as you can imagine
        Dim try2 = (From q In DC.TestTbl1s
                    Where concLst.Contains(q.p & "|" & q.i)
                    Select q).ToList

        '3: Works! - much faster that example 2, but requires double DB call, and returns unnecessary data. 
        Dim try3tmp = (From q In DC.TestTbl1s
                    Where p_lst.Contains(q.p)
                    Select q).ToList
        Dim try3 = (From q In try3tmp
                    Where concLst.Contains(q.p & "|" & q.i)
                   Select q).ToList

        '4: Any better solutions ???
    End Using
End Sub
Class PriKeys   'Class to hold the clients primary key collection
    Private _p As Integer
    Public Property p() As Integer
        Get
            Return _p
        End Get
        Set(ByVal value As Integer)
            _p = value
        End Set
    End Property
    Private _i As Integer
    Public Property i() As Integer
        Get
            Return _i
        End Get
        Set(ByVal value As Integer)
            _i = value
        End Set
    End Property
End Class

SQL测试数据:

CREATE TABLE TestTbl1 (p int, i int)
INSERT INTO TestTbl1 VALUES(1,1)
INSERT INTO TestTbl1 VALUES(1,2)
INSERT INTO TestTbl1 VALUES(1,3)
INSERT INTO TestTbl1 VALUES(2,1)
INSERT INTO TestTbl1 VALUES(3,1)

(如果已发布针对此特定问题的SO解决方案,我道歉,我无法找到/或理解它)

1 个答案:

答案 0 :(得分:0)

当我拥有像这样的语句动态时,我已经非常成功地使用了LINQkit。

http://www.albahari.com/nutshell/linqkit.aspx

您想要查看谓词构建器。