LINQ的多/单个实例到SQL的DataContext [英] Multiple/single instance of Linq to SQL DataContext

查看:215
本文介绍了LINQ的多/单个实例到SQL的DataContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多不同类别的查询和一套共同的表修改数据的一个项目。我已经成立了一个.dbml文件它为我们提供了DataContext类。我的问题是在DataContext的单个实例是否应使用多个实例的所有对象,或者是否可以安全使用。我也想知道如何在单个的DataContext的情况下,线程安全,并获得它的方法是否应该是同步的。

I have a project with a number of different classes querying and modifying data in a common set of tables. I've set up a .dbml file which provides us with a DataContext class. My question is whether a single instance of the DataContext should be used by all objects, or whether multiple instances are safe to use. I'm also wondering about thread safety in the case of a single DataContext, and whether access to it's methods should be synchronized.

推荐答案

里克施特拉尔大约有你的选择一个好的文章:<一href=\"http://www.west-wind.com/weblog/posts/246222.aspx\">http://www.west-wind.com/weblog/posts/246222.aspx.

Rick Strahl has a nice article about your options: http://www.west-wind.com/weblog/posts/246222.aspx.

参见:<一href=\"http://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live\">http://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live.

您可能希望部署的每种类型稍微不同的战略 - 网络,桌面,窗口服务...

You may want a slightly different strategy for each type of deployment - web, desktop, windows service...

总结,你的选择是:


  • 全球的DataContext - 危险在多线程环境(包括Web应用程序)。请记住,实例成员不能保证是线程安全的(从布拉德利Grainger的<一个href=\"http://stackoverflow.com/questions/196253/linq-to-sql-where-does-your-datacontext-live#196264\">answer以上)。

  • 每个线程的DataContext - 复杂。如果您的DataContext正在跟踪的变化,你必须确保在适当的时间来刷新它们。实例化,存储和检索DataContext的是一种痛苦。

  • 每个原子操作的DataContext - 你失去跟踪变化的能力,因为一个DataContext的创建,而另一个更新的对象或删除它。附加一个数据对象到一个新的DataContext可能无法工作像您期望。

  • 每个数据对象的DataContext - 因为你有在DataContext大惊小怪的实例化(创建和附加)和更新/删除(把它关闭数据对象和使用它),似乎不雅

我选择了每个数据对象一个DataContext。它可能不是最高档的解决方案,但它在所有部署环境中正常工作。

I opted for a DataContext per data object. It may not be the fanciest solution but it works in all deployment environments.

这篇关于LINQ的多/单个实例到SQL的DataContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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