6

我当前的应用程序正在使用基于实例的数据访问层。我用连接字符串实例化层。然后我调用一个方法来执行某种命令。例如,有一种方法可以填充数据集。基本上,我传递存储过程和任何 SQL 参数并取回数据集。有一个静态类来处理我的数据访问还是基于实例更好?我确实有一个包含对象的域层,但我没有像 ORM 那样映射对象。我将对象传递给工厂,然后实例化数据层以拉回数据集。然后我将数据集映射到对象。我计划更新我的应用程序(是的,迁移到 C#),但我没有时间改变整个事情。我对插入更新和删除做同样的事情。如果我现在所做的一切正常,请告诉我。您认为这种方法有什么问题吗?否则,我该怎么办?我没有写这门课。我在网上找到了它,并认为这是我需要的。

以下是数据类的示例:

Public Sub New(ByVal connectionString As String)
        _connectionString = connectionString
    End Sub

Public Function FillDataset(ByVal cmd As String, ByVal cmdType As CommandType, Optional ByVal parameters() As SqlParameter = Nothing) As DataSet
        Dim connection As SqlConnection = Nothing
        Dim command As SqlCommand = Nothing
        Dim sqlda As SqlDataAdapter = Nothing
        Dim res As New DataSet
        Try
            connection = New SqlConnection(_connectionString)
            command = New SqlCommand(cmd, connection)
            command.CommandType = cmdType
            AssignParameters(command, parameters)
            sqlda = New SqlDataAdapter(command)
            sqlda.Fill(res)
        Catch ex As Exception
            'CreateDataEntry(ex, WriteType.ToFile, cmd)
        Finally
            If Not (connection Is Nothing) Then connection.Dispose()
            If Not (command Is Nothing) Then command.Dispose()
            If Not (sqlda Is Nothing) Then sqlda.Dispose()
        End Try
        Return res
    End Function

         Public Function ExecuteNonQuery(ByVal spname As String, ByVal ParamArray parameterValues() As Object) As Object
        Dim connection As SqlConnection = Nothing
                    Dim command As SqlCommand = Nothing
        Dim res As Object = Nothing
        Try
            connection = New SqlConnection(_connectionString)
            command = New SqlCommand(spname, connection)
            command.CommandType = CommandType.StoredProcedure
            command.Parameters.AddRange(parameterValues)
            connection.Open()
            command.ExecuteNonQuery()
            res = command.Parameters(command.Parameters.Count - 1).Value
         Catch ex As Exception
            CreateDataEntry(ex, WriteType.ToFile, spname)
            If Not (transaction Is Nothing) Then
                transaction.Rollback()
            End If                
        Finally
            If Not (connection Is Nothing) AndAlso (connection.State = ConnectionState.Open) Then connection.Close()
            If Not (command Is Nothing) Then command.Dispose()                
        End Try
        Return res
    End Function
4

2 回答 2

7

首先,我认为基于实例的方法是正确的。使用静态类会使对 DAL 进行单元测试以及在对其他类进行单元测试时模拟 DAL 变得更加困难。其次,我认为您应该重新考虑构建自己的 DAL。您将通过使用现有的(经过充分测试的)ORM(如 LINQtoSQL、nHibernate、nTier 甚至实体框架)在可能的情况下投入大量时间来创建、维护和测试 DAL,将更多时间花在直接有利于您的业务需求的代码。我已经完成了手工构建的 DAL 和 ORM,在我的例子中是 LINQtoSQL,我发现我花费更少的时间测试(和修复)我的 DAL 去 ORM 路线。

于 2009-03-14T19:18:51.130 回答
1

实例基础更灵活。

您可以更轻松地更改底层技术(只需提供不同的实现)。

您还可以代理数据访问层。就我而言,我最近这样做是为了检查本地数据库中是否存在某些内容,如果没有,则从远程数据库获取它的副本,然后将其存储在本地。这对应用程序的其余部分完全透明。

于 2009-03-15T00:10:16.000 回答