如何通过使用LINQ TO SQL将表名作为参数传递来获取表记录计数

时间:2012-08-24 13:35:36

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

我有一个名为getTableRecordCount的方法。

 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,我可以使用相同的方法获取其他表 记录数。有关如何实现这一目标的任何意见?

2 个答案:

答案 0 :(得分:0)

您可以创建一个传递数据上下文和表达式的方法。 然后从数据上下文(基于Linq2Sql,因为您没有指定框架),您可以使用

获取表
GetTable<T>() 

关于数据上下文的方法。

表达式将是您的参数。

希望它有所帮助。

答案 1 :(得分: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