私は以下のコードに従ってDapper
を使用してデータにアクセスします。関数は2つしかありませんが、実際のコードはhundreadを持つことができます。私はすべてのSQL文を特定のデータベーステーブルにログインさせたいと思います。これは、すべてのDataRepositoryクラス関数で共通でなければなりません。
SelectCustomers
、 SelectEmployees
などの各単一の関数内でそれを繰り返さないように、そのような機能を実装する最善の方法は何ですか?例を共有してください。
Public Class BaseRepository
Protected Shared Function OpenConnection() As IDbConnection
Dim connection As IDbConnection
connection = New SqlConnection(MyAppSettings.PascomDB)
connection.Open()
Return connection
End Function
End Class
Public Class DataRepository
Inherits BaseRepository
Public Function SelectCustomers() As IEnumerable(Of Customers)
Using connection As IDbConnection = OpenConnection()
Dim query As String = "SELECT * FROM Customers"
Return connection.Query(Of Customers)(query)
connection.Close()
End Using
End Function
Public Function SelectEmployees() As IEnumerable(Of Employees)
Using connection As IDbConnection = OpenConnection()
Dim query As String = "SELECT * FROM Employees"
Return connection.Query(Of Employees)(query)
connection.Close()
End Using
End Function
End Class
単純なままにして、基本クラスにメソッドを追加するだけです。
Public Class BaseRepository
' ...
Protected Shared Function LogAndQuery(Of T)(query As String) As IEnumerable(Of T)
Using connection As IDbConnection = OpenConnection()
' TODO: add logging of the query here
Return connection.Query(Of T)(query)
' connection.Close() - note, this is unreachable code, but it's being disposed anyway
End Using
End Function
End Class
あなたのリポジトリメソッドでそれを使う:
Public Function SelectCustomers() As IEnumerable(Of Customers)
Dim query As String = "SELECT * FROM Customers"
Return LogAndQuery(Of Customers)(query)
End Function