Entity Framework - How should I instance my "Entities" object

Viewed 3329

I'm a total newbie at Entity Framework and ASP.Net MVC, having learned mostly from tutorials, without having a deep understanding of either. (I do have experience on .Net 2.0, ADO.Net and WebForms)

My current doubt comes from the way I'm instancing my Entities objects.

Basically I'm doing this in my controllers:

public class PostsController : Controller {

    private NorthWindEntities db = new NorthWindEntities();

    public ActionResult Index() {
            // Use the db object here, never explicitly Close/Dispose it
    }
}

I'm doing it like this because I found it in some MSDN blog that seemed authoritative enough to me that I assumed this was a correct way.
However, I feel pretty un-easy about this. Although it saves me a lot of code, I'm used to doing:

using (NorthWindEntities db = new NorthWindEntities() {
}

In every single method that needs a connection, and if that method calls others that'll need it, it'll pass db as a parameter to them. This is how I did everything with my connection objects before Linq-to-SQL existed.

The other thing that makes me uneasy is that NorthWindEntities implements IDisposable, which by convention means I should be calling it's Dispose() method, and I'm not.

What do you think about this?
Is it correct to instance the Entities object as I'm doing? Should it take care of its connections by opening and closing them for each query?
Or should I be disposing it explicitly with a using() clause?

Thanks!

2 Answers

You are making a good point here. How long should the ObjectContext live? All patterns and practises books (like Dino Esposito's Microsoft-NET-Architecting-Applications) tell you that a DataContext must not live long, nor should it be cached.

I was just wondering why not having, in your case, a ControllerBase class (I'm not aware of the MVC implementation, so bear with me) where the ObjectContext gets initiated once for all controller. Especially think about the Identity Map Pattern, that's already implemented by Entity Framework. Even though you need to call another controller as your PostsController, it would still work with the same Context and improve performance as well.

Related