うまくいけば、私の 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