Reputation: 19396
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.
Upvotes: 1
Views: 1690
Reputation: 12857
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...
Upvotes: 2