Override entity framework connection logic

Topics: EF Runtime
Jan 9, 2013 at 6:47 PM

Sorry for cross-posting (from here), but I haven't gotten a satisfactory answer from Stack Overflow...

I'm using EF 5 and I need to somehow hack into the connection creation pipeline. Here's my situation. In production, we have 2 SQL servers (I don't have any control over this) which I have specified in my web.config. If one connection fails, I need to try the other one. Once again, I know about SQL failover clustering but like I said, I have no control over that.

I tried using the DbContext overload which takes a DbConnection. Then I tried to open the connection myself to see if it's successful, then pass it on to EF. The problem there was that EF only wants a closed connection. And it seems really hokey to open a connection, then close it, only to have EF open it again!

Is there a better way??


Jan 10, 2013 at 4:43 PM

Unfortunately in EF5 you would have to pass a closed connection to DbContext and then open it before using it.

The good news is that EF6 will have two features that should help you. First, EF6 now allows you to pass an open connection to DbContext. This change made it into the alpha 2 pre-release of EF6 which is available on NuGet.

The second change is "connection resiliency" which is currently being developed and should make it into nightly builds and pre-release versions in the coming months. Connection resiliency is primarily focused on handling SQL Azure connections, but it is intended to be pluggable/extendable such that you should be able to handle other cases such as yours if an appropriate behavior for detecting the failure and retrying is plugged in.


Marked as answer by BriceLambson on 10/3/2013 at 3:44 PM
Jan 10, 2013 at 5:10 PM

Awesome, that's just what I wanted to hear!  I will definitely take a peek at EF6a2.  That'll give me some async lovin' too. :)

Thanks again, Arthur!