0

I am grabbing the underlying connection from my ObjectContext. I need to check the state of the connection and open it if necessary. I am wondering whether I need to close it or if this will be taken care of for me.

I am disposing of my context anyway, which I assume is closing the connection.

Should I be opening this connection manually in the first place?

FYI: I am purposely avoiding the convenience methods ExecuteStoredCommand and ExecuteStoredQuery. We have some older code that works against the old ADO.NET classes. I just want to expose the connection and make sure it's ready to use.

user5071535
  • 1,312
  • 8
  • 25
  • 42
Travis Parks
  • 8,435
  • 12
  • 52
  • 85

2 Answers2

1

Entity Framework manages opening and closing connections itself. Normally, it will close a connection when it's finished a command. So before using the connection, you'll have to check the connection state and open it when it's closed. And you can close it (not dispose it!) when you're done.

When the context is disposed, the connection is always closed.

You may have to enclose your code in a TransactionScope if you want your legacy code and Entity Framework's to run in one transaction.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • I didn't know if opening and closing the connection would have performance impacts. Does Entity Framework open and close the connection for each command it runs? – Travis Parks Feb 27 '13 at 17:29
  • As far as I know, yes. But the connection pool manages the real connection to the database, so in many cases the real connection may not even have been closed. See e.g. [this post](http://stackoverflow.com/q/861552/861716). – Gert Arnold Feb 27 '13 at 17:43
  • I created a simple connection manager class implementing `IDisposable`. – Travis Parks Feb 27 '13 at 17:54
  • Is this a web application, if so, normally, you manage connection based on http request, open it when http request comes in, and close it when it close. You don't need create a new class, ObjectContex or DbContext already serves that purpose – J.W. Feb 27 '13 at 18:03
  • I am using Ninject's `InRequestScope` to limit the lifetime of my context. The problem is that the connection in `ObjectContext` isn't opened until it is first used. Occasionally, the old code is first to run. – Travis Parks Feb 27 '13 at 18:20
  • But does it matter who's first? If you've got a hold of the connection, you can open it. – Gert Arnold Feb 27 '13 at 18:23
0

I think if you dispose the context, it will close the connection for you. And if you create a new ObjectContext,the connection will be opened as well.

J.W.
  • 17,991
  • 7
  • 43
  • 76