1

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Technology Lover
  • 259
  • 1
  • 7
  • 19

2 Answers2

2

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.

Aage
  • 5,932
  • 2
  • 32
  • 57
  • thank you very much for your clear explanation. I really appreciate it. Would you kindly tell me what will happen if the database is offline while I am connecting to the Entity Framework via Using block? If an error will occur, could you please tell me how I can display a proper error message? – Technology Lover Nov 10 '13 at 14:55
  • If the database would be offline you would get a SqlException because of a timeout, but the `using` statement doesn't have anything to do with that. If this does occur, you could nest the `using` in a `try, catch, finally` block and pass a message back to the UI. But why would you expect the database to be offline in the first place? – Aage Nov 11 '13 at 09:44
2

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

Community
  • 1
  • 1
Dmytro
  • 1,590
  • 14
  • 14
  • thank you very much for your clear explanation. Since I am using Using block, would you kindly tell me what will happen if the database is offline while I am connecting to the Entity Framework via Using block? If an error will occur, could you please tell me how I can display a proper error message? – Technology Lover Nov 10 '13 at 14:56
  • @TechnologyLover, updated my answer, please check, if it is what you expect to see. – Dmytro Nov 10 '13 at 15:25