我有一个非常简单的WinForms /实体框架(V6)程序:实体框架 - 离开DB语境下打开VS不断地重新创建
- 查询数据库来填充表单元素
- 一旦用户点击,再查询数据库来获得相关信息,这些信息
- 进行计算,并显示给用户
作为一个新手,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 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
当我交换的东西这样的工作方式,它似乎有增加的速度大幅提升,我知道,这让我开到可能做出错误的更改DB的可能性,但这是一个不做任何更新的小型项目 - 只是查询......这是一个合理的解决方案,或者这是一种危险的做事方式吗?
一般而言,您应该以某种工作单位的方式使用DBContext,否则数据可能会随着数据库上下文缓存实体而变得过时。如果您执行相同的查询两次,它只会触及DB一次。我广泛使用了EF,从来没有发现以这种方式使用上下文是昂贵的。我会做更多的调查,看看你的放缓。 – 2014-08-28 13:55:44
我也很好奇,如果重新创建DBContext继承类是昂贵的。在repo中的每个函数使用自己的DBContext实例之前,我已经建立了一个存储库。在那里似乎没有任何问题,但再次,该应用程序不是很密集的数据。请看这篇关于使用EF实现Unit of Work模式的文章:http://www.asp。net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4 /实现存储库和工作单元模式-asp-net-mvc-application – erdinger 2014-08-28 14:01:00
如果您不需要更改加载的数据(并将其写回数据库),则应考虑关闭对上下文的更改跟踪(ctx.Configuration.AutoDetectChanges = false)。这应该会给你一个明显的性能提升。 – 2014-08-28 14:05:28