4

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.

4

1 回答 1

2

我反编译ObjectResult<T>(EF4。)这是它的Dispose()方法。它正在创建其他托管对象,例如DbDataReader. 和一个称为 a 的内部对象Shaper,它可以拥有一个数据库连接。

如果你处理它,你相信它知道它在做什么。如果你不这样做,你相信自己知道它在做什么,不做什么,以及为什么。我会小心翼翼地处理它。

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;
}
于 2018-01-25T00:24:33.840 回答