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

时间:2015-12-11 18:30:00

标签: .net vb.net dry

我添加了以下类来从数据库加载特定的DataTable。 DataTable仅在首次需要时加载,但在程序打开的剩余时间内仍然可用。它对于很少改变的查找表很有用,但每次使用程序时我都不一定需要。

效果很好,但我需要几张类似的表格。我喜欢的是让这个类更通用/可重复使用,这样我就不会复制/粘贴其中几十个,只更改属性的名称。有什么建议吗?

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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

可以通过调用GetTable函数来使用表格:

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

我使用Enum来避免拼写错误或调用未定义的表。