.net – 实体框架 – 保留DB Context Open vs不断重新创建

前端之家收集整理的这篇文章主要介绍了.net – 实体框架 – 保留DB Context Open vs不断重新创建前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个相当简单的 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

我发现的是那部分似乎正在减慢我的程序(如果我错了,请纠正我 – 正如我所说,我是新手)我正在重新建立一个新的数据库连接每次我使用:

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

当我以这种方式切换工作时,它似乎显着提高了速度,我知道它让我可能对数据库进行不良更改,但这是一个不做任何事情的小项目更新 – 只是查询……这是一个合理的解决方案还是这是一种危险的做事方式?

数据库连接通常将在几乎任何现代查询工具的连接池中汇集.这看起来很像线程池;将打开一定数量的连接,并且每当创建新上下文并请求连接时,它将被独占使用其中一个现有连接.当处理上下文时,连接将不会被关闭,它将被返回到连接池.

因此,没有必要尝试长时间手动保持上下文活动.只需一次操作即可使用它们.

当然,如果您明确地不希望它发生,则可以禁用连接池,但很少有这样做的原因.

猜你在找的VB相关文章