System.InvalidOperationException: Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.

System.InvalidOperationException: Unexpected connection state. When using a wrapping provider ensure that the StateChange event is implemented on the wrapped DbConnection.

System.Data.Entity.Core.EntityException: The underlying provider failed on Open. ---> System.TimeoutException: Timeout in IO operation

开发windows 服务 使用EF6遇到的坑!

1、有时候调试停个一两分钟,然后继续调试可能就会出现这个错误,然后无法连接数据库。

2、其它未知错误也可能会引发该错误。

解决办法:创建一个新的DbContext即可解决

/** 

      //Aotufac依赖注入 配置接口依赖
       builder.RegisterType<MyModel>().As<DbContext>();//每次调用生成一个dbcontext对象

       //注册将当前程序集的类
        builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
          .AsImplementedInterfaces().AsSelf();
       _container = builder.Build(); 

       /// <summary>
        /// 从Autofac容器获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetFromFac<T>()
        {
            //DependencyResolver.Current.GetService<ClassType>()
            return _container.Resolve<T>();
        }

**/

var mydbcontext;//构造函数注入

try{

   //你执行的代码。。。。。

   mydbcontext.xxxx();

}catch(System.InvalidOperationException inverr)

{

    mydbcontext =GetFromFac<MyModel>();//重新获取一个dbcontext对象,如果不是用的autofac  重新new 一个dbcontext对象

    //Creating a new db-context solved the problem.

   //创建一个新的DbContext即可解决

}

 如果是打开一个web网页报这样的错,重新打开一个页面,但是windows服务不可能每次都去重启,只能重新创建连接

原文地址:https://www.cnblogs.com/pzxnet/p/13094340.html