37

When initialize an entity framework context.

One is to initialize at class level, such as

public class EntityContactManagerRepository
    : ContactManager.Models.IContactManagerRepository
{
    private ContactManagerDBEntities _entities = new ContactManagerDBEntities();

    // Contact methods
    public Contact GetContact(int id)
    {
        return (from c in _entities.ContactSet.Include("Group")
                where c.Id == id
                select c).FirstOrDefault();
    }
}

The other way is to initialize at the method level.

public class EntityContactManagerRepository
    : ContactManager.Models.IContactManagerRepository
{    
    // Contact methods
    public Contact GetContact(int id)
    {
       using (var entities = new ContactManagerDBEntities())
           return (from c in entities.ContactSet.Include("Group")
               where c.Id == id
               select c).FirstOrDefault();
    }
}

From an Ado.Net background, I prefer the later one-initialize in method, but the first one is from the example developed by Stephen Walthe. Or another question, does it matter at all?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
J.W.
  • 17,991
  • 7
  • 43
  • 76

3 Answers3

31

It does matter, because the context controls the lifetime of change tracking data, and also impacts which object instances you can link together when you edit the objects, since objects on two different contexts cannot have a relationship with each other. It looks to me like the examples you're sharing come from an ASP.NET MVC application. In this case, I generally use one entity context per request, since requests are short-lived, and since it's common, when updating an object in a request, to have to fetch other objects and create relationships between them.

On the other hand, you don't want to keep an entity context around for a long time, because it will chew up memory as it tracks changes to more and more objects.

This may seem like an argument for the "one context per class" option, but it isn't, really. It's more like an argument for "one context per unit of work."

Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • 1
    Appreciate your reply. "I generally use one entity context per request, since requests are short-lived." Sounds like you also prefer it into the method level, since that's binding to the request. – J.W. Jun 30 '09 at 14:46
  • 1
    I don't do it at the method level because the "method per request" is a controller action, and my controllers don't know about object contexts. For me, the context is instantiated inside the service which creates the repository/repositories needed by the controller. But you've got the general idea. – Craig Stuntz Jun 30 '09 at 15:03
  • usually what I do is have a helper class that returns an instance of the context, that sticks around for the life of the request. You can store a reference to it in the Current HttpContext (HttpContext.Current). – John B Jul 01 '09 at 14:44
  • From your comment I understand that you do initialize the context at your service's class level (not method level), because you'd be doing new MyServiceClass() inside the controller on every request. Am I right? – BornToCode Jan 07 '16 at 17:00
  • @BornToCode I just set it as request scoped in the DI composition root. – Craig Stuntz Jan 11 '16 at 15:05
7

Generally speaking: it's context per request in ASP.NET and context per window in WinForms/WPF.

There's an article that explains quite well the reasoning behind the context per request paradigm: Entity Framework Object Context Scope

IT Helper
  • 69
  • 1
  • 1
2

Well, the "best" way is always subjective. However, adding a UnitOfWorkScope class to the project can simplify things greatly - namely you don't have to think too much about creating the object context or persisting the Unit of Work back to the database.

There is a great article that explains How To Create a Unit of Work Scope.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212