When I instantiate a DbContext, I sometimes, but rarely am getting this exception. (Like once a week.)
[InvalidCastException: Unable to cast object of type 'System.Data.Entity.Core.Objects.ObjectContext' to type 'System.Data.Entity.DbContext'.]
System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.get_Context() +86
System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter.Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext) +88
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Action`2 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +373
System.Data.Entity.Infrastructure.Interception.DbConnectionDispatcher.Open(DbConnection connection, DbInterceptionContext interceptionContext) +503
System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +18
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +234
System.Data.Entity.Core.EntityClient.EntityConnection.Open() +318
[EntityException: The underlying provider failed on Open.]
System.Data.Entity.Core.EntityClient.EntityConnection.Open() +738
System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection(Boolean shouldMonitorTransactions) +167
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +60
System.Data.Entity.Core.Objects.<>c__DisplayClass59.<ExecuteStoreCommand>b__57() +118
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +206
...
...
The DbContext that I'm instantiating inherits from a base DbContext that I wrote. In that constructor I do this:
this.Database.Log = s => this.sqlLogger.Debug(s);
this.Database.ExecuteSqlCommand(Resources.SqlServerConnectionInit); // throws here
I'm using EF 6.1.3.
When I look at the Microsoft code, in DatabaseLogFormatter.cs, I just totally don't see how it's possible for this exception to happen. I just don't see how that variable could actually be a System.Data.Entity.Core.Objects.ObjectContext.
This code is being run in a web app. And once this exception happens, it will continue to happen - always - until I restart the web server. Restarting the database server doesn't fix anything.
I have found absolutely nothing on the internet about this.
FYI: SQL Server is the database server.