如何在Entity Framework中实现IDisposable?(How to implement IDisposable in Entity Framework?)

我在一个单独的EL层中有我的实体框架上下文,它代表实体层,然后我移动到DAL,然后BL和我的用户接口aspx.cs代码页。 我很困惑,如此使用IDisposable相同。 到目前为止,我正在做什么,在我的DAL中,我有我的实体的背景。

namespace abc { public class Action: IDisposable { Entities context = new Entities(); // all the methods public void Dispose() { context.Dispose(); } } }

这样做是否正确? 我只是一个天真的程序员,所以帮助我学习相同的逻辑。

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. I am confused as such how to use IDisposable in the same. What I am doing till now, supopose in my DAL I have context of my entities.

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.

最满意答案

我个人会稍微改变它,例如:虽然我在实体框架中实现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; } } }

Personally I would change it a little bit, such as: Although I have very little experience with implementing the IDisposable within the Entity Framework.

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; } } }

更多推荐