如果数据上下文是静态的? [英] Should data contexts be static?
问题描述
我使用实体框架4和我创建一个的DataContext 在基类中的一个典范。但我是在分析它,并正在创建上下文每次我尝试查询时间,所以我想使它成为静态,以便它仅创建一次,总是重复使用。
I am using entity framework 4 and I create an datacontext for model in one of the base classes. But I was in profiling it and the context is being created every time I try to query, So I thought of making it static so that it is created only once and reused always.
你觉得这是做IT和数据/对象上下文应经常进行静态的最好方法?是否有任何缺点使其静态的?应的数据的上下文是静态或非静态?任何意见或建议,欢迎。
Do you think this is the best way to do it and data/object context should always be made static? Are there any disadvantages to making it static? Should data contexts be static or non-static? Any ideas or suggestions are welcome.
推荐答案
没有。他们不应该永远是静态的。
No. They should not always be static.
您可以实际运行中使用静态数据上下文,而不是非静态等效(比如从单独的会话多个用户有更多的问题访问从多个线程在同一上下文)。
You can actually run in to many more issues with a Static Data Context rather than the non-static equivalent (like multiple users from separate sessions accessing the same context from multiple threads).
我不打算进入详细的解释,因为有一些很不错的博客文章在那里覆盖的细节:
I'm not going to go into the detailed explanation since there are some very good blog posts out there covering the details:
LINQ到SQL的DataContext生命周期管理 - 里克·斯特劳的Web日志(似乎不是相关的,但仍然是)
Linq to SQL DataContext Lifetime Management - Rick Strahl's Web Log (may not seem relevant, but still is)
的使实体框架(V1)的工作,第1部分:终身的DataContext管理(一个可能的选择,如果你不喜欢里克的解决方案)
Making Entity Framework (v1) work, Part 1: DataContext Lifetime Management (for a possible alternative if you don't like Rick's solution)
这篇关于如果数据上下文是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!