我正在尝试使用 PetaPoco 为 ASP.NET Web 表单项目生成我的 DAL 层。
Namespace Eva.Dal.Polls
Public Partial Class EVAMOD_PL_CategoryDb
Private db As Eva.Dal.Core.EvaDb
Public Function Insert(a As EVAMOD_PL_Category) As Object
Return db.Insert(a)
End Function
Public Sub New()
db = New Eva.Dal.Core.EvaDb
End Sub
End Class
Public Partial Class EVAMOD_PL_GL_CategoryDb
Private db As Eva.Dal.Core.EvaDb
Public Function Insert(a As EVAMOD_PL_GL_Category) As Object
Return db.Insert(a)
End Function
Public Sub New()
db = New Eva.Dal.Core.EvaDb
End Sub
End Class
End Namespace
特别是我对如何打开数据库感兴趣。在 PetaPoco 网站上有这个例子
// Create a PetaPoco database
objectvar db=new PetaPoco.Database("connectionStringName");
// Show all articles
foreach (var a in db.Query<article>("SELECT * FROM articles")){
Console.WriteLine("{0} - {1}", a.article_id, a.title);
}
但是在 PetaPoco 附带的 T4 生成器中,有一个不错的部分,它与所有 DTO 一起生成类似
Namespace Eva.Dal.Core
Public Partial Class EvaDb
Inherits Database
Public Sub New()
MyBase.New("ConnectionString")
CommonConstruct()
End Sub
Public Sub New(connectionStringName As String)
MyBase.New(connectionStringName)
CommonConstruct()
End Sub
Private Partial Sub CommonConstruct()
End Sub
Public Interface IFactory
Function GetInstance() As EvaDb
End Interface
Public Shared Property Factory() As IFactory
Get
Return mFactory
End Get
Set
mFactory = Value
End Set
End Property
Private Shared mFactory As IFactory
Public Shared Function GetInstance() As EvaDb
If istance IsNot Nothing Then
Return istance
End If
If Factory IsNot Nothing Then
Return Factory.GetInstance()
Else
Return New EvaDb
End If
End Function
<ThreadStatic> _
Shared istance As EvaDb
Public Overrides Sub OnBeginTransaction()
If istance Is Nothing Then
istance = Me
End If
End Sub
Public Overrides Sub OnEndTransaction()
If istance Is Me Then
istance = Nothing
End If
End Sub
Public Class Record(Of T As New)
Public Shared ReadOnly Property Repo() As EvaDb
Get
Return EvaDb.GetInstance()
End Get
End Property
Public Function IsNew() As Boolean
Return Repo.IsNew(Me)
End Function
.......
End Class
End Class
End Namespace
那么使用 PetaPoco 创建我的 DB 对象并在 DAL 层中使用它的正确方法是什么?
另外,我读到 PetaPoco 有一种方法可以保持连接打开并重用它,我想这对于 BLL/DAL 架构是不可行的,例如,当您从 BLL 进行 2-3 次操作访问数据库时?或者如果是,那么应该如何正确处理?创建一个打开连接并执行所有 2-3 操作的 DAL 方法?由于在 BLL 中打开连接不应该是这种情况。