2012-08-24 47 views
1

我有一個名爲getTableRecordCount的方法。如何獲取表記錄計數通過傳遞表名作爲參數使用LINQ TO SQL

Public Function getTableRecordCount(ByVal strTableName As String, ByVal iParam1 As Integer, iParam2 As Integer) As Boolean 


     Try 
      Dim detailReturned = (From paramTableName In dc.<need to pass the strTableName here> 
            Where paramTableName.col1 = iParam1 And paramTableName.col2 = iParam2 
            Select paramTableName).Count 

      If (detailReturned > 0) Then 
       Return True 
      Else 
       Return False 
      End If 

     Catch ex As Exception 
      ..... 
     End Try 

    End Function 

如果我可以通過表名和擁有的DataContext我可以用得到其他表 記錄計數的方法相同。有關如何實現這一目標的任何輸入?

+0

我認爲這可以幫助:LINQ to SQL的:動態SQL表名(http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/6273d072-f500-4382- afb4-8eafd185794d /) –

+0

有點偏離主題,但'任何'而不是'Count'在這裏效率更高。 –

回答

0

您可以創建一個傳遞數據上下文和表達式的方法。 然後從數據上下文(基於LINQ2SQL因爲你沒有指定框架),你可以通過使用

GetTable<T>() 

方法對數據方面得到的表。

表達式將是您的參數。

希望它有幫助。

0

希望我的VB沒關係;我在C#中更舒適。我不確定這是否適用於LINQ to SQL,但靠近底部的GetTableRecordCount測試通過。我假設你在表中使用不同的數據類型,因此是通用方法。

Imports System.Text 
Imports System.Linq.Expressions 

Class Product 
    Public Id As Integer 
    Public Name As String 
    Sub New(id As Integer, name As String) 
     Me.Id = id 
     Me.Name = name 
    End Sub 
End Class 

Class Order 
    Public Id As Integer 
    Public NumberOfItems As Integer 
    Sub New(id As Integer, numItems As String) 
     Me.Id = id 
     Me.NumberOfItems = numItems 
    End Sub 
End Class 

Class DataContext 
    Public Property Products As IEnumerable(Of Product) 
    Public Property Orders As IEnumerable(Of Order) 
    Sub New() 
     Me.Products = New Product() {New Product(1, "Apple"), New Product(2, "Banana")} 
     Me.Orders = New Order() {New Order(1, 20), New Order(2, 50)} 
    End Sub 
End Class 

<TestClass()> 
Public Class Main 
    Dim MyDataContext As DataContext 

    <TestMethod()> 
    Public Sub GetTableRecordCount() 
     Me.MyDataContext = New DataContext() 
     Assert.IsTrue(Me.GetTableRecordCount(Of Product)("Products", Function(p) p.Id, 1, Function(p) p.Name.Length, 5)) 
     Assert.IsTrue(Me.GetTableRecordCount(Of Order)("Orders", Function(o) o.Id, 2, Function(o) o.NumberOfItems, 50)) 
    End Sub 

    Private Function GetTableRecordCount(Of TRow)(tableName As String, getParam1 As Func(Of TRow, Integer), iParam1 As Integer, getParam2 As Func(Of TRow, Integer), iParam2 As Integer) As Boolean 
     Try 
      Dim propertyExpr = Expression.Property(Expression.Constant(Me.MyDataContext), tableName) 
      Dim getTableData = Expression.Lambda(Of Func(Of IEnumerable(Of TRow)))(propertyExpr).Compile() 

      Dim detailReturned = 
      From row In getTableData() 
      Where getParam1(row) = iParam1 And getParam2(row) = iParam2 
      Select row 

      Return detailReturned.Count() > 0 

     Catch ex As Exception 
      Return False 
     End Try 

    End Function 
End Class 
相關問題