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

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

问题描述

我正在使用实体框架4,并且在其中一个基类中为模型创建了一个数据文本。但是我正在分析它,并且每次我尝试查询时都会创建上下文,所以我想到使它成为静态,这样它只创建一次,并且始终被重用。

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终身管理 - Rick Strahl的Web日志(可能看起来不相关,但仍然是)

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天全站免登陆