[英]How to implement IDisposable in Entity Framework?
I am having my entity framework context in a separate EL Layer, which stands for Entity Layer and then I move to DAL, then BL and my user inteface aspx.cs code page. 我将实体框架上下文放在单独的EL层中,该层代表实体层,然后移至DAL,然后移至BL和用户界面aspx.cs代码页。 I am confused as such how to use IDisposable in the same. 我很困惑如何同时使用IDisposable。 What I am doing till now, supopose in my DAL I have context of my entities. 到目前为止,我正在做的事情是,在我的DAL中假设我拥有我的实体的上下文。
namespace abc
{
public class Action: IDisposable
{
Entities context = new Entities();
// all the methods
public void Dispose()
{
context.Dispose();
}
}
}
Is it the correct way of doing so? 这是正确的方法吗? I am just a naive programmer so help me in learning the same logic. 我只是一个天真的程序员,所以请帮助我学习相同的逻辑。
Personally I would change it a little bit, such as: Although I have very little experience with implementing the IDisposable
within the Entity Framework. 我个人会对其进行一些更改,例如:尽管我在实体框架中实现IDisposable
经验很少。
namespace abc
{
public class Action: IDisposable
{
private bool _disposed;
Entities context= new Entities();
// all the methods
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
context.Dispose();
// Dispose other managed resources.
}
//release unmanaged resources.
}
_disposed = true;
}
}
}
Well in general, yes, your Dispose
method should dispose of all resources that implement IDisposable
as well as unmanaged resources (files, etc.) 好吧,总的来说,是的,您的Dispose
方法应该处理实现IDisposable
的所有资源以及非托管资源(文件等)。
However, it it usually not a good design to hold on to an EF context as a resource . 但是,将EF上下文作为资源坚持通常不是一个好的设计。 You will likely have better success if you create a Context
within your Action
methods and dispose of it when you're done with it. 如果在Action
方法中创建一个Context
并在完成后将其处理,则可能会获得更好的成功。 Then, if that's your only resource, you don't need to implement IDisposable
at all . 那么,如果这是你唯一的资源,您并不需要实现IDisposable
根本 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.