数据上下文应该是静态的吗? [英] Should data contexts be static?

查看:26
本文介绍了数据上下文应该是静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架 4,并在其中一个基类中为模型创建了一个 datacontext.但是我在分析它并且每次尝试查询时都会创建上下文,所以我想将它设为 static 以便它只创建一次并始终重用.

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.

您认为这是最好的方法吗?数据/对象上下文应该始终保持静态吗?使它成为静态有什么缺点吗?数据上下文应该是静态的还是非静态的?欢迎提出任何想法或建议.

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 to SQL DataContext Lifetime Management - Rick Strahl 的网络日志(可能看起来不相关,但仍然是)

Linq to SQL DataContext Lifetime Management - Rick Strahl's Web Log (may not seem relevant, but still is)

使实体框架 (v1) 发挥作用,第 1 部分:DataContext 生命周期管理(如果您不喜欢 Rick 的解决方案,则提供一个可能的替代方案)

Making Entity Framework (v1) work, Part 1: DataContext Lifetime Management (for a possible alternative if you don't like Rick's solution)

这篇关于数据上下文应该是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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