我有一个相当简单的
Winforms / Entity Framework(v6)程序:
原文链接:https://www.f2er.com/vb/255279.html>查询数据库以填充表单元素
>用户单击后,重新查询数据库以获取相关信息
>对该信息执行计算并将其显示给用户
作为一名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
我发现的是那部分似乎正在减慢我的程序(如果我错了,请纠正我 – 正如我所说,我是新手)我正在重新建立一个新的数据库连接每次我使用:
Using ctx As New MyEntities ... End Using
在我的代码中.
因此,我正在考虑做的是将表单级变量ctx作为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
当我以这种方式切换工作时,它似乎显着提高了速度,我知道它让我可能对数据库进行不良更改,但这是一个不做任何事情的小项目更新 – 只是查询……这是一个合理的解决方案还是这是一种危险的做事方式?