How to implement IDisposable in Entity Framework?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 18:27:29

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

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.

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