Joh*_*tos 7 .net vb.net entity-framework
我有一个相当简单的Winforms/Entity Framework(v6)程序:
作为一名EF新手,我试图跟踪我在网上发现的事情的例子,并提出了一些相当简单的东西,用于填充/查询:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using ctx As New MyEntities
<Query DB to populate initial values for first combobox>
End Using
End Sub
Private Sub cboVal1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboVal1.SelectedIndexChanged
Using ctx As New MyEntities
<Queries to populate the other controls based upon user selections>
End Using
End Sub
Private Sub Button_Press(sender As Object, e As EventArgs) Handles MyButton.Click
Using ctx As New MyEntities
<Queries to get data, based upon user selections for calculations>
End Using
End Sub
Run Code Online (Sandbox Code Playgroud)
我发现的是那部分似乎正在减慢我的程序(如果我错了,请纠正我 - 正如我所说,我是新手)我正在重新建立一个新的数据库连接每次我使用:
Using ctx As New MyEntities
...
End Using
Run Code Online (Sandbox Code Playgroud)
在我的代码中.
所以,我正在考虑做的是拥有一个表单级变量ctx as MyEntities- 在表单加载上建立连接并关闭表单关闭时的连接,并始终使用相同的连接......以下内容:
Dim ctx as MyEntities
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ctx = New MyEntities
<Query ctx to populate initial values for first combobox>
End Sub
Private Sub cboVal1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboVal1.SelectedIndexChanged
<Queries ctx to populate the other controls based upon user selections>
End Sub
Private Sub Button_Press(sender As Object, e As EventArgs) Handles MyButton.Click
<Queries ctx to get data, based upon user selections for calculations>
End Sub
Private Sub Main_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
ctx.Dispose()
ctx = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)
当我以这种方式切换工作时,它似乎已经大大提高了速度,我知道它让我可能对数据库做出错误的更改,但这是一个不做任何事情的小项目更新 - 只是查询......这是一个合理的解决方案还是这是一种危险的做事方式?
数据库连接通常将在几乎任何现代查询工具的连接池中进行池化.这看起来很像线程池; 将打开一定数量的连接,并且每当创建新的上下文并请求连接时,它将被独占使用其中一个现有连接.处理上下文时,连接将不会关闭,它只会返回到连接池.
因此,没有必要尝试长时间手动保持上下文活动.只需一次操作即可使用它们.
当然,如果您明确地不希望它发生,则可以禁用连接池,但很少有理由这样做.