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

查看:72
本文介绍了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?

我最初的想法是我希望连接的打开时间尽可能短,但是考虑到页面加载的速度有多快,我花费更多的时间打开和关闭这些连接而不是保持连接打开所需要的资源? /p>

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?

推荐答案

要考虑的一件事:DataContext的生存期不会影响SQL Server连接保持打开状态的时间.仅当您评估查询时,才执行由Linq To Sql生成的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.

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

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数据源最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆