Search code examples
c#entity-frameworkidisposableusing-statement

Which is the better, an instance variable or a local variable for an EF context?


I know that the title looks a bit bad :) But I dont know how to explain my problem..

This is typically a basic problem for me but I dont know answer..

I am writing a server application which is using eneter library for client-server communinication and also it has a DAL gets data from database. as it a server application, it always need to communicate with database, so I dont know which way is more effective. (approx, max 50 clients will be connected to server)

I am using entity framework and created a model from my mysql db.

the first code is here

    private MyEntities ent;

    public DbHelper()
    {
     ent = new MyEntities();
    }

   void Foo()
  { 
       ent.Mytable.where......
       ....

  }

and second type code is

    void Foo()
    {
        using (MyEntities ent = new MyEntities())
        {
            ent.Mytable.where...
        }

    }

Can I use using statement or create a global instance variable for dal class and use it for each functions.. ?


Solution

  • Better yet, implement IDisposable on your DAL class:

    public sealed class MyDal implements IDisposable
    {
        private MyEntities ent = new MyEntities();
    
        void Foo()
        { 
           ent.Mytable.where......
           ....
    
        }
    
        public void Dispose()
        {
            ent.Dispose();
        }
    }
    

    Then...

    using(var dal = new MyDal())
    {
        dal.Foo();
        //....
    }
    

    Take a read here about why my IDisposable is sealed.