实体框架ObjectContext的再次使用 [英] Entity Framework ObjectContext re-usage

查看:141
本文介绍了实体框架ObjectContext的再次使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习EF和有关于ObjectContext中的问题:

I'm learning EF now and have a question regarding the ObjectContext:

我应该为每个查询(功能)创建的ObjectContext的实例时,我访问数据库?

Should I create instance of ObjectContext for every query (function) when I access the database?

或者最好是一次(单身)创建并重复使用?

Or it's better to create it once (singleton) and reuse it?

EF之前,我使用企业库数据访问块,并创造dataacess的实例数据访问功能...

Before EF I was using enterprise library data access block and created instance of dataacess for DataAccess function...

推荐答案

绝对是每个查询。它是一个轻量级的对象,所以有每次你需要它的时间制作一个不发生太大的成本。

Definitely for every query. It's a lightweight object so there's not much cost incurred creating one each time you need it.

此外,时间越长你保持一个ObjectContext的活着,更多的缓存的对象将包含你对它运行的查询。这可能会导致内存问题。因此,具有ObjectContext的作为单是一个特别糟糕的主意。随着应用程序正在使用您加载越来越多的实体在单身的ObjectContext直到最后你有在内存整个数据库(除非你分离的实体,当你不再需要它们)。

Besides, the longer you keep an ObjectContext alive, the more cached objects it will contain as you run queries against it. This may cause memory problems. Therefore, having the ObjectContext as a singleton is a particularly bad idea. As your application is being used you load more and more entities in the singleton ObjectContext until finally you have the entire database in memory (unless you detach entities when you no longer need them).

再有就是可维护性问题。有一天,你试图寻找一个错误,但不能找出其中的数据加载导致它。

And then there's a maintainability issue. One day you try to track down a bug but can't figure out where the data was loaded that caused it.

这篇关于实体框架ObjectContext的再次使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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