Bahaïka
Bahaïka

Reputation: 725

Entity framework good practices

I'm currently using Entity Framework to create a WebSite in asp.net, and I was wondering what is the good way to instantiate the Entity Container ?

Currently, I'm doing this (where MyDB is my entity framework container) :

public partial class User : System.Web.UI.MasterPage
{
     private myDb ctx;
      protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack) ctx = new myDb();
     }
}

And I use the context in many functions.

But, on many websites, I saw this way to handle it :

using (var ctx = new myDb())
{
}

But if use the second one I have to put it in many functions of my class. And so re-instantiate the Entity Container.

What is better? Could you explain me why it is better, and if both are good, why do I have to use one more than the other in different cases.

Upvotes: 1

Views: 799

Answers (2)

ekim boran
ekim boran

Reputation: 1819

The pratice of disposing Entity Container comes from habbit of disposing expensive resources like sql connections to the database like

 using (SqlConnection connection = new SqlConnection(connectionString))
 {}

However, the Entity Framework is intelligent enough to open connections only when queries are executed so the Entity Container does not represent an sql connection. So there is no real advantage in this sense, apart from collecting the garbage a little earlier.

Moreover, if you are disposing the context you cannot use lazy loading. More information is here Entity Framework - Load Reference Keys after disposing entity object context

In summary, I can not see any disadvantage of one context per request approach. In contrast, no lazy loading is a pretty important downside to me.

Upvotes: 2

Mario S
Mario S

Reputation: 11945

I thought I'd add my comments as an answer instead.

In your case, you could call ctx.Dispose(); in the Page_Unload event and achieve the same effect as

using (var ctx = new myDb()) 
{ 
}

using works on classes implementing IDisposable. When the using block finishes, the .Dispose() method is called. And you dispose an object to release the resources and free up memory. The database object in your sample inherits from DbContext and implements IDisposable, so when Dispose() is called it will also close the connection to the database.

This will of course get handy if you have a lot of requests. You don't want thousands of open connections to the database and a lot of memory occupied.

One thing to look out for is if there are any unhandled exceptions thrown before Page_Unload, then the unload event won't be fired and the database object not disposed.

Then it's better to use a using since it always calls .Dispose() on objects.

Upvotes: 1

Related Questions