views:

213

answers:

2

Looking at Code First in ADO.Net EF 4 CTP 3 and wondered how the SqlConnection in their walkthrough is disposed. Is that the responsibility of ContextBuilder? Is it missing from the example?

  var connection = new SqlConnection(DB_CONN);
  var builder = new ContextBuilder<BloggingModel>();
  var connection = new SqlConnection(DB_CONN);

  using (var ctx = builder.Create(connection))
  {
      //... 
  }
A: 

Close and Dispose in SqlConnection are functionally equivalent. Therefore, as long as the connection is closed -- and I think you'll find that it is, but don't take my word for it -- the sample code works.

But since you asked, you should probably dispose of it anyway. It will do no harm, and will stop others from asking the same question.

Craig Stuntz
@Craig: I know that disposing the connection will also close it, but the sample code disposes ctx, not connection. It's unknown (to me) whether the contract for ContextBuilder ensures that it will dispose (and therefore close) the connection it's given.
Eric J.
Let me rephrase: Because the ContextBuilder closes the connection, the connection does not need to be disposed.
Craig Stuntz
@Craig: ContextBuilder did not close the connection in my test (see my separate answer).
Eric J.
+1  A: 

I just realized that I can add an event handler to ObjectContext.Disposing and resolve this.

In CTP 3 at least, Connection is not disposed when the ObjectContext is disposed.

Since I'm subclassing ObjectContext already, I implemented IDisposable in my subclass and call Connection.Dispose() from there.

Eric J.

related questions