Linq to SQL数据源的最佳实践[英] Linq to SQL data source best practice

本文是小编为大家收集整理的关于Linq to SQL数据源的最佳实践的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在我的项目中使用 linq to SQL 时,我目前在代码执行中尽可能晚地创建数据上下文并尽快处理它.这会导致数据上下文在一个页面上多次打开和关闭.

另一种选择是在页面加载时打开数据类并在页面卸载时处理它,这样连接只会打开和关闭一次.

这两种方法在优化方面是否存在显着差异,还是一种代表最佳实践?

我最初的想法是,我希望连接打开的时间尽可能短,但考虑到页面加载速度有多快,我在打开和关闭这些连接上花费的时间比保持打开连接所消耗的资源值得吗?

推荐答案

需要考虑的一点:DataContext 的生命周期不会影响 SQL Server 连接保持打开状态的时间.您的 Linq To Sql 生成的 SQL 语句仅在您评估查询时执行.

因此,当您调用(例如).ToList() 或调用 .DataBind() 时,SQL 语句就会运行.连接在那个时候打开和关闭.

本文地址:https://www.itbaoku.cn/post/1557072.html

问题描述

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?

推荐答案

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.