Instantiating a context in LINQ to Entities

Posted by Jagd on Stack Overflow See other posts from Stack Overflow or by Jagd
Published on 2009-05-01T21:52:56Z Indexed on 2010/04/16 5:23 UTC
Read the original article Hit count: 414

I've seen two different manners that programmers approach when creating an entity context in their code.

The first is like such, and you can find it all over the MSDN code examples:

public void DoSomething() {
     using TaxableEducationEntities context = new TaxableEducationEntities()) {
          // business logic and whatever else
     }
}

The second is to create the context as a private attribute in some class that encapsulates your business logic. So you would have something like:

public class Education_LINQ {

        private TaxableEducationEntities context = new TaxableEducationEntities();

        public void DoSomething() {
            var result = from a in context.luAction
                         select a;

            // business logic and whatever else
        }
}

Which way is more efficient?

Assume that you have two methods, one called DoSomething1() and another called DoSomething2(), and both methods incorporate the using statement to open the context and do whatever with it. Were you to call one method after the other, would there be any superfluous overhead going on, since essentially both methods create the context and then clean it up when they're done? As opposed to having just one private attribute that is created when a class object is instantiated, and then in turn cleaned up when the object goes out of scope?

© Stack Overflow or respective owner

Related posts about linq-to-entities

Related posts about entity-framework