Iti Tyagi
Iti Tyagi

Reputation: 3671

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. 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.

Upvotes: 2

Views: 5797

Answers (2)

CuccoChaser
CuccoChaser

Reputation: 1079

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

Upvotes: 4

D Stanley
D Stanley

Reputation: 152624

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.

Upvotes: 2

Related Questions