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...