2011-08-23 64 views
1

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

然后,我需要从数据库中选择所有等于我存储在内存中的主键列表中的记录。

我认为下面的(简化的)例子会给你一个我想要存档的概念,你可以看到我已经找到了一个方法,但我希望有人有更好的解决方案? :-)

.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溶液已经被发送,我只是找不到它或了解它)

回答