实体框架4 ObjectContext生命周期 [英] Entity Framework 4 ObjectContext Lifetime

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

问题描述

我刚开始使用具有存储库模式的EF4。每次使用上下文或包装代码之后,我必须调用dispose方法。我可以在我写的每个方法中使用ObjectContext,而不是在存储库中处理这个方法。

此外,我也不想将UI从UI传递到存储库。

解决方案

使用对象上下文的一般模式是:

  public BusinessObject GetSomething(){
using(MyObjectContext context = new MyObjectContext()){
//..do fun stuff
}

}

希望您正在使用的模式。当您只能使用使用语句时,调用处理似乎有点过分。



另一个选项是如果要在流中执行多个数据库查询。我看到一个模式,您可以在线程中重用相同的上下文。人们基本上实现了一个基于Thread的单例模式,并绕过上下文。这样做的优点是不需要重建上下文,还有一些在内存缓存中。你可能遇到并发问题。有人更新您在EF内部缓存的内容。



我猜测第二种情况并不适用,因为这听起来像是在写一个小应用程序。 (该声明基于您对UI传递上下文的意见...一个声明,会吓倒任何好的代码架构师)。



如果你对一个线程感兴趣基于单例。首先了解 Singleton 模式,然后查看这个 blog 关于DataContext的线程。您将不得不将DataContext类型更改为ObjectContext类,但它将工作。



编辑



我会说我忽略了一个明显的解决方案,这将在下面;)。只需使用基于属性的对象上下文,并在使用语句中播放您的存储库。这将与上述使用示例相同,但您将实现IDisoposable。


Ive just started using EF4 with the repository pattern. Im having to call the dispose method after every use of context or wrap code arround in the using block. Can I use the ObjectContext without doing this in every method I write or is there a better way of handling this in the repository.
Also I dont want to pass the ObjectContext to the repository from the UI as well.

解决方案

The general pattern for using an object context is:

public BusinessObject GetSomething(){
   using (MyObjectContext context = new MyObjectContext()){
      //..do fun stuff
   }

}

Which hopefully is the pattern you are using. Calling dispose seems a little overkill when you can just use a "using" statement.

Another option is if you are going to be doing multiple DB queries in a flow. I have seen a pattern where you can reuse the same context within the thread. People basically implement a Thread based singleton pattern and pass around the context. Advantages to this is not having to rebuild the context, as well as some in memory caching. Downside is you could run into concurrency issues. Someone updating something that you have cached internally in EF.

I am guessing the second case doesn't really apply because it sounds like you are writting a small app. (that statement was based on your comments about passing a context from UI...a statement which will scare any good code architect).

If you are interested in a thread based singleton. First learn about the Singleton pattern, and then check out this blog about "DataContext" threads. You will have to change the "DataContext" type to the ObjectContext class but it would work.

EDIT

I will say I overlooked an obvious solution and that would be the below ;). Just using a property based Object Context and playing your repository in a using statement. It would be the same as the using example above, but you would implement IDisoposable.

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

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