2011-08-23 74 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溶液已經被髮送,我只是找不到它或瞭解它)

回答