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.