扩展此过程以根据需要加载各种数据表

Extend this procedure to load various data tables as needed

我添加了以下 class 以从数据库加载特定的 DataTable。 DataTable 仅在第一次需要时加载,然后在程序打开的其余时间保持可用。它对于很少变化的查找表很有用,但我不一定每次使用程序时都需要。

效果不错,但我需要几张类似的表格。我想要的是使这个 class 更多 generic/reuseable 这样我就不会只有几十个这样的 copy/pasted 除了属性的名称改变之外什么都没有。有什么建议吗?

Public Class StatesService
    Private Shared _statesDataTable As DataTable
    Private Shared _initLock As Object = New Object()

    Public Shared ReadOnly Property StatesDataTable() As DataTable
        Get
            If (_statesDataTable Is Nothing) Then InitializeData()
            Return _statesDataTable
        End Get
    End Property

    Private Shared Sub InitializeData()
        SyncLock _initLock
            If (_statesDataTable Is Nothing) Then
                _statesDataTable = DB.GetStatesFromDatabase()
            End If
        End SyncLock
    End Sub

End Class

您可以使用来自非共享 class 的对象实例,而不是拥有多个共享 class。但是在您需要能够通过 tableName 或其他一些可以分隔不同表的特定 属性 从 DB class 中获取 DataTable 的实例之前:

Public Class DbLockService

    Private _dt As DataTable
    Private _initLock As Object = New Object()
    Public TableName As String

    Sub New(ByVal tableName As String)
        Me.TableName = tableName
    End Sub

    Public ReadOnly Property Table As DataTable
        Get
            If _dt Is Nothing Then
                Me.InitializeData()
            End If
            Return _dt
        End Get
    End Property

    Private Sub InitializeData()
        SyncLock _initLock
            _dt = db.GetTableByItsName(Me.TableName)
        End SyncLock
    End Sub

End Class

然后这样定义和调用表:

    Dim StatesTable As New DbLockService("StatesTable")
    dgv.DataSource = StatesTable.Table

这是我想出的。第一次需要 table 时,它是从数据库加载的。然后可以供任何后续使用。

Imports System.Collections.Generic

Public Class CommonData
    Private Shared _initLock As Object = New Object()
    Private Shared _tableDictionary As Dictionary(Of Tables, DataTable)

    Public Shared Function GetTable(table As Tables) As DataTable
        If _tableDictionary Is Nothing Then
            _tableDictionary = New Dictionary(Of Tables, DataTable)
        End If

        If Not _tableDictionary.ContainsKey(table) OrElse _tableDictionary(table) Is Nothing Then
            InitializeData(table)
        End If

        Return _tableDictionary(table)
    End Function

    Private Shared Sub InitializeData(table As Tables)
        SyncLock _initLock

            Dim dt As DataTable = DB.GetDataFor(table)
            dt.TableName = table.ToString

            If _tableDictionary.ContainsKey(table) Then
                _tableDictionary.Remove(table)
            End If

            _tableDictionary.Add(table, dt)

        End SyncLock
    End Sub

    Public Enum Tables
        States
        TimeZones
        Options
    End Enum

End Class

一个table可以通过调用GetTable函数来使用:

dgvStates.DataSource = CommonData.GetTable(CommonData.Tables.States)

我使用枚举来避免拼写错误或调用未定义的 tables。