How to implement IDisposable in Entity Framework?

牧云@^-^@ 提交于 2019-12-12 09:01:25

问题


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.


回答1:


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



回答2:


Well in general, yes, your Dispose method should dispose of all resources that implement IDisposable as well as unmanaged resources (files, etc.)

However, it it usually not a good design to hold on to an EF context as a resource. 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. Then, if that's your only resource, you don't need to implement IDisposable at all.



来源:https://stackoverflow.com/questions/15160200/how-to-implement-idisposable-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!