1

Well, I am not really know when or how is dispose the data context. For example, I have this code:

try
{
    using(MyEntities myDbContext = new MyEntities())
    {
         //My code that get entities from data base and work with them
    }
}
catch
{
    throw;
}

In this case, if I am not wrong, if all go well, the data context is disposed. However, if in my code something goes wrong and an exception is thrown, is my data context disposed?

For this reason, I am thinking on another option:

using(MyEntities myDbContext = new MyEntities())
{
    try
    {
        //My code
    }
    catch
    {
        myDbContext.Dispose;
        throw;
    }
}

In this case, I dipose the dbcontext in the catch, so I think that is disposed. But I don't know if this is a good solution or there are others options.

Which is the best way to handled exceptions with dbContext and free resources (mainly, data base connection)?

thank so much.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • 1
    just wrap each resource (context, connection etc) in an `using`. Do not call `.Dispose`. Do not add `try`/`catch`. – Remus Rusanu Dec 31 '14 at 17:14
  • 1
    if you are using a `using` then there is nothing to worry about. it will will be disposed 100% – T McKeown Dec 31 '14 at 17:14
  • 1
    you might find this helpful - http://stackoverflow.com/questions/8309877/if-an-exception-happens-within-a-using-statement-does-the-object-still-get-dispo – aw04 Dec 31 '14 at 17:15
  • Ok, then with the using is enough, but I have one dobut. If I need to caputre and exception, such as concurrency exception, is the same that the using is insede the try o better the try inside the using? – Álvaro García Dec 31 '14 at 19:05

1 Answers1

2

This is all you need to do to ensure Dispose()

using(MyEntities myDbContext = new MyEntities())
{
     //My code that get entities from data base and work with them
}

which is equivalent to but not as elegant:

MyEntities myDbContext = new MyEntities();
try{
  ... (your code)
}
finally{
   myDbContext.Dispose();
}

It doesn't matter if an exception is thrown, caught or not caught...

T McKeown
  • 12,971
  • 1
  • 25
  • 32