Linq to SQL 数据源最佳实践
在我的项目中使用 linq to SQL 时,我目前正在代码执行中尽可能晚地创建数据上下文并尽快对其进行处理。这会导致数据上下文在页面上多次打开和关闭。
另一种选择是在页面加载时打开数据类,并在页面卸载时将其处置,以便连接仅打开和关闭一次。
两种方法之间的优化是否存在显着差异,或者其中一种方法是否代表最佳实践?
我最初的想法是,我希望连接打开的时间尽可能短,但考虑到页面加载的速度,我在打开和关闭这些连接上花费的时间是否比保持连接打开所花费的资源要多?
When using linq to SQL in my project I am currently creating the data context as late as possible in the code execution and disposing it as soon as possible. This results in the data context being open and closed many times on a page.
Another option is to open the data class on page load and dispose it on page unload so the connection is only opened and closed once.
Is there a significant difference in the optimization between the two methods or does one represent a best practice?
My original thought was that I wanted the connection open as little time as possible but considering how fast a page load is am I costing myself more time in opening and closing these connections than the resource hit of keeping it open is worth?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要考虑的一件事是:
DataContext
的生命周期不会影响 SQL Server 连接保持打开状态的时间。仅当您评估查询时才会执行 Linq To Sql 生成的 SQL 语句。因此,当您调用(例如).
ToList()
或调用.DataBind()
时,就会运行 SQL 语句。连接将在此时打开和关闭。One thing to consider: the
DataContext
's lifetime doesn't effect how long the SQL Server connection is kept open. The SQL statement generated by your Linq To Sql is only executed when you evaluate your query.So when you call (for example), .
ToList()
, or call.DataBind()
, then the SQL statement is run. The connection is opened and closed at that time.LinQ to SQL 管理器在幕后使用连接池 IIRC。
因此,除非您以某种方式明确终止连接,否则这不应该是您关心的问题。
Behind the scenes the LinQ to SQL manager uses a connection pool IIRC.
So unless you explicitly kill the connection somehow that should not be your concern.