在与数据库无关的体系结构中处理不同的 DbType 枚举,如何



这是我目前的设置:

Public Interface IDatabase
   Function CreateParameter(name as String, dbType as <dbTypeEnumeration>)
End Interface
Public Class OracleDatabaseRepository
    Implements IDatabase
    Public Function CreateParameter(ByVal name As String, ByVal dbtype As <dbTypeEnumeration>) As Object
    End Function
End Class
Public Class SQLServerRepository
    Implements IDatabase
    Public Function CreateParameter(ByVal name As String, ByVal dbtype As <dbTypeEnumeration>) As Object
    End Function
End Class
Public Class DatabaseService
    Private _rep As IDatabase
    Sub New(ByRef rep As IDatabase)
        _rep = rep
    End Sub
    Public Function CreateParameter(ByVal name As String, ByRef dbtype As <dbTypeEnumeration>) As Object
       _rep.CreateParameter(name, dbtype)
    End Function
End Class

这里的问题是dbTypeEnumeration到底是什么。在上面的例子中,它只是我的问题的一个占位符。由于我们同时使用 Oracle 和 SQL Server 数据库,因此 DbType 会根据所使用的数据库而有所不同。对于 Oracle,OracleClient 对象具有自己的 OracleDbType 枚举和类型。SQL Server 也有自己的枚举。

我的问题是:是否可以根据注入到 DatabaseService 构造函数中的存储库来显示这些特定于数据库的枚举?如果没有,最好的方法是什么?我想分离两个数据库,共享逻辑,并允许将来开发,因为接口作为该开发的代码协定。

撇开存储库实现的正确性不谈,我会改变DbType抽象的级别。

interface与数据库无关。

Public Interface IDatabase
    Function CreateParameter(ByVal name As String, ByVal type As Type) As Object
End Interface

数据库约束实现应该在你的具体Repository本身。您还想如何保持它的通用性,但在两种类型之间仍然有所不同?

Public Class SqlServerRepo : Implements IDatabase
    Private Shared typeLookup As Dictionary(Of Type, Data.SqlDbType) = New Dictionary(Of Type, SqlDbType)
    Shared Sub New()
       (...Fill the dict according to your specification ...)
    End Sub
    Public Function CreateParameter(name As String, type As Type) As Object Implements IDatabase.CreateParameter
        Dim concreteDbType = typeLookup(type)
        (.. your parameter creation here ..)
    End Function
End Class
Public Class OracleServerRepo : Implements IDatabase
    Private Shared typeLookup As Dictionary(Of Type, OracleType) = New Dictionary(Of Type, OracleType)
    Shared Sub New()
        (...Fill the dict according to your specification ...)
    End Sub
    Public Function CreateParameter(name As String, type As Type) As Object Implements IDatabase.CreateParameter
        Dim concreteDbType = typeLookup(type)
         (.. your parameter creation here ..)
    End Function
End Class

尽管您的类中包含"存储库"一词,但它们并没有真正遵循存储库设计模式。 请查看此 MSDN 存储库设计模式的详细说明。 存储库应返回表示应用程序域的实体/对象,而不是特定于数据库的信息(即 dbType)。 存储库封装来自数据库详细信息的用户,并将处理将数据库类型转换为适当的 .NET 类型。

最新更新