I've started using Entity Framework (database first), and I noticed that the methods the tt template generates for the context class (for stored procedures) have a return type ofObjectResult.
This type is IDisposable, but no sample code I can find actually calls the Dispose method. Is there a reason for this?
I currently don't have the "using" on the stored procedure call as I do further IEnumerable related stuff on the result (essentially just projecting the result set), but I could easily refactor that.
My question is, should I be using a pattern like the following if I have no reason to keep the connection to the database open:
using (var context = new DatabaseContext())
{
using (var result = context.spMyStoredProcedure(param1, param2))
{
return result.ToList();
}
}
I've seen some advice that even disposing the DbContext might not be needed, but there seems to be a lot of inconsistencies even on MSDN on what to do.
I decompiled ObjectResult<T>
(EF4.) Here's its Dispose()
method. It's creating other managed objects, like a DbDataReader
. and an internal object called a Shaper
that can own a database connection.
If you dispose it, you're trusting it to know what it's doing. If you don't, you trust yourself to know what it's doing, not doing, and why. I'd play it safe and dispose it.
public override void Dispose()
{
DbDataReader reader = this._reader;
this._reader = (DbDataReader) null;
this._nextResultGenerator = (NextResultGenerator) null;
if (reader != null && this._readerOwned)
{
reader.Dispose();
if (this._onReaderDispose != null)
{
this._onReaderDispose((object) this, new EventArgs());
this._onReaderDispose = (Action<object, EventArgs>) null;
}
}
if (this._shaper == null)
return;
if (this._shaper.Context != null && this._readerOwned)
this._shaper.Context.ReleaseConnection();
this._shaper = (Shaper<T>) null;
}