使用 ASP.NET Web 应用程序处理 LINQ to SQL 中的数据上下文

发布于 2024-11-14 11:47:56 字数 394 浏览 5 评论 0原文

我在 ASP.NET Web 应用程序中使用数据上下文。

 ComponentDBDataClassesDataContext db = new ComponentDBDataClassesDataContext();
 int ifUserExists = (from result in db.Customers where (userName == result.UserName) && (password == result.Password) select result.UserName).Count();

每次使用数据上下文时都应该关闭它吗?如果是这样我为什么要关闭它?如果不应该关闭为什么?

有人能给我一些详细而清晰的解释吗?

谢谢你的期待

I'm using Data context in my ASP.NET web application.

 ComponentDBDataClassesDataContext db = new ComponentDBDataClassesDataContext();
 int ifUserExists = (from result in db.Customers where (userName == result.UserName) && (password == result.Password) select result.UserName).Count();

Should I close the data context every time i use it ? If so why should I close it ? If it should not be closed why ?

Can some one give me some elaborate and clear explanation?

Thank you in anticipation

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

提笔书几行 2024-11-21 11:47:56

当您拥有 DataContext 时,它可以帮助您跟踪从其表检索或附加到表的对象的更改。

因此,您可能不应该每次都关闭数据上下文,但除非您依赖数据上下文来跟踪所有更改 - 并且您有一个类似单例的实例,否则您应该通过使用 每个操作的实例和提交/回滚。否则你会因为换轨而占用大量内存。

但我认为很难对你的问题给出简单的是/否的答案。

When you have a DataContext it helps you tracking changes in objects that has been retrieved from its tables or attached to the tables.

So you probably shouldn't close the datacontext every time, but unless you rely on the datacontext to track all you changes - and you have a singletone like instance, you should probably limit the lifetime of each instance by using the instances and submit/rollback on each operation. Otherwise you will occupy a lot of memory for the track changing.

But I think it is difficult to give a simple yes/no answer to your question.

悲凉≈ 2024-11-21 11:47:56

关于这一点已经有很多文章了。一般来说,我建议您为每个工作单元坚持使用一个数据上下文。因此,每次使用时都将其包装在 using() 中。

看看这里有一篇不错的文章:
http:// www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management

或者在 stackoverflow 上:
我应该何时处置数据上下文

A lot has been written about this already. In general I advise you to stick to one datacontext for earch unit-of-work. So wrap it in using() everytime you use one.

Have a look here for a nice article:
http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management

Or on stackoverflow:
When should I dispose of a data context

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文