views:

1019

answers:

2

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?

A: 

The second option actually does not clean up after itself if that's what you mean. I prefer the using ObjectContext version every time because I don't have to dispose it after. Not sure I got the question right though... Too many hours programming today.

public class UserManagerRepository : IUserManagerRepository, IDisposable
{
    private readonly Entities _context = new Entities();
    private bool _disposed;

    public User Create(User user, int countryId)
    {
     user.Country = GetCountry(countryId);
     _context.AddToUser(user);
     _context.SaveChanges();
     return user;
    }
}

Then to use this repository I do something like:

using(var repository = new UserManagerRepository())
{
    repository.Create(user);
}
mhenrixon
OK, bad assumption on my part; I should have realized that the entity context doesn't get cleaned up, but maybe that's not even a big deal. I tend to incorporate the using() statement as well when I do it. What prompted this question is that I ran into an MVC tutorial that Scott Guthrie did, and he created the entity context as a private attribute to the class that it was being used in.
Jagd
It depends on how complex your model/domain is. In some cases I have had need for sending the current object context around. I had some really complicated creation of invoices or something a while ago. I let the factory take the context in the constructor so that I could reuse it. I do think however that you can get away with the above most of the time.
mhenrixon
+11  A: 

Creating a new ObjectContext each time does involve 'some' overhead. Essentially the overhead involved is copying metadata from a global cache into metadata associated with the specific ObjectContext.

This overhead is relatively minor, so often it is not worth worrying about, especially when you consider the extra safety inherent in the using pattern.

For me which option you choose depends upon things like:

  1. How long lived is your wrapping class likely to be? If it lives for a long time the ObjectContext might grow to hold a lot of entities slowing down over time. So a new ObjectContext each time might be a good idea.
  2. Are calls to the methods on your wrapping class synchronized? The ObjectContext class itself is not threadsafe so if you use the second pattern you need to make sure your wrapping class / repository is thread safe if you expect multiple threads to call it.
  3. Are the methods essentially unrelated? If so you might get unexpected side-effects if they share one context between the methods.

In general my recommendation is that if the methods are stateless, i.e. fire and forget a new context for each method is probably a good idea.

If however you have a relatively short lived stateful form or something then maybe a shared context is a better idea.

Hope this helps

Alex

UPDATE: I've taken the time to put together a more complete answer here

Alex James
+1 for the blog post http://blogs.msdn.com/alexj/archive/2009/05/07/tip-18-how-to-decide-on-a-lifetime-for-your-objectcontext.aspx
bendewey
great question, great answer +1 for both
ram
how about caching EntityConnection? http://stackoverflow.com/questions/2575485/managing-entityconnection-lifetime
kervin