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服務不可能每次都去重啟,只能重新創建連接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM