Question

I am a new .NET developer and I am using LINQ-to-Entities for my first time. As I am practicing a lot on it, I would like to ask you about the entity framework a question that I could not find its solution on Google. Since I am connecting to the entities in my code as following:

using(MyEntities context = new MyEntities())

Why should I use Using block for connecting to the Entities? Is there any way like defining a Helper class to take care of this?

Was it helpful?

Solution

You use using statements to make sure any resources you are done with get disposed of, so they don't use any memory when they don't need to. If you would have many connections to Entity Framework (EF) open (for instance), your app could consume a whole lot of memory and cause some trouble on the machine it's running on.

A using statement calls Dispose() on an object that implements IDisposable (an interface). You could avoid using the using statement by calling Dispose() explicitly. (But you might forget, so it's easy to just use the using for an object that you want to dispose once you're done with it.)

You could setup a connection in a helper class, by, for instance, using a Singleton Pattern to make sure you only ever have one object with an Entity Connection at the most. But in the case of EF this might cause other problems with tracking by EF. You could also setup a Repository (C# EF Repository Pattern) that is the only class to open and close these connections to EF and keeps it neatly in one place.

OTHER TIPS

using is a handy shortcut to say .Dispose() at the end of object's usage. It wraps your code in try-finally block, so, even if exception will occur, all object resources (like opened connection, etc.) will be disposed. This is necessary, since connection, for example, is really limited resource, and should be treated with care.

So instead of coding manually

//Define context object here
try
{
    //Do some job, which might lead to exception
}
finally
{
    context.Dispose();
}

you're doing just simple

using(var context = new MyEntities())
{
    //Do some job, which might lead to exception
}   //Resources will be disposed here

Efficiently it's same. But more easy to write. Additionally, you can (and mostly should, it's good practice) apply using to object of any class, which implements IDisposable interface.

Some readings: Entity Framework and context dispose

Entity Framework 4 - lifespan/scope of context in a winform application //though about winforms, still interesting discussion

http://msdn.microsoft.com/en-us/library/system.idisposable%28v=vs.110%29.aspx

Using only makes sure that your unmanaged resources will be safely disposed at the end of using block. You don't need to make manual dispose in finally block. Normal exception handling is still necessary to organize. It's up do you, how to do it.

 try
 {
    using(var context = new MyEntities()) //Connection is not opened yet...
    {
        var data = context.Collection.ToList(); //Here Entity will try to open connection.
        //If it's impossible, you will have EntityException. 
    }   //Resources will be disposed here
 }
 //Something about entity
 catch(EntityException ex)
 {
     //Let's log it...
     Logger.Log.Error("Some problem with entity...", ex);
     //Show message, or notify user in other way
     MessageBox.Show("Problem with database.");
 }
 //You don't know, what happened, but will check log
 catch(Exception ex)
 {
     Logger.Log.Error("Unknown problem...", ex);
     //Show message, or notify user in other way
     MessageBox.Show("Problem. If it will persist, contact your admins");
 }

But it's only stub. What really should be done, depends heavily on your application and db access architecture...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top