EF6與Mysql疑難問題記錄

來源:互聯網
上載者:User

標籤:文檔   rac   mysq   調用   需要   系統   work   自動遷移   strong   

這幾天公司架構調整,新的迭代後端使用了ABP架構與CodeFirst模式,執行過程中遇到了一個非必現很難定位的問題,特此記錄。

 

現象

 

在程式訪問MySql資料庫時報了異常

 

System.InvalidOperationException: The default DbConfiguration instance was used by the Entity Framework before the ‘MySqlEFConfiguration‘ type was discovered. An instance of ‘MySqlEFConfiguration‘ must be set at application start before using any Entity Framework features or must be registered in the application‘s config file. 

 

在StackOverflow上找了很多解決方案,都找不到可靠的原因分析,折騰許久終於在官方文檔上找到了答案。

 

 

原因


先來看下官方文檔的一段解釋:

(https://msdn.microsoft.com/en-us/data/jj680699#Moving)

 

There are some situations where configuration may be needed before any DbContext type has been used. Examples of this include:

 

  • Using DbModelBuilder to build a model without a context
  • Using some other framework/utility code that utilizes a DbContext where that context is used before your application context is used

 

In such situations EF is unable to discover the configuration automatically and you must instead do one of the following:

 

  • Set the DbConfiguration type in the config file, as described in the Moving DbConfiguration section above
  • Call the static DbConfiguration.SetConfiguration method during application startup

 

 

 在括弧內給出的官方文檔地址中包含了兩種指定DbContext配置的方式:

    一,Config節點

    二,DbConfigurationType特性標註在DbContext上

 

我們選擇的是第二種方式,即指定類型後自動設定的方式。程式碼片段如下:

 

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]    public class SHMedicalRecordDbContext : AbpDbContext    {        ......    }

 

這在獨立項目中是毫無問題的,但混入以前的項目就出現了開題所報的錯誤,問題如官方那段解釋中某些不會自動設定的情況之二:某些架構或通用代碼在程式調用DbContext之前就使用了它。

怎麼理解這個問題,我們項目組的情況是:

遺留系統也用了EF6,新迭代所開發的系統需要嵌入老系統來使用,那麼在老系統中就存在了兩個DbContext,如果新系統的DbContext先被初始化,那程式不會有問題。

若遺留系統的Context先初始化,就符合了官方描述的情況之二,所以出現了異常。(新系統的初始化採用的多線程啟動,所以前後順序每次啟動服務都不一樣)

 

解決方案

 

解決方案也在剛才那段文字的下面,採用Config或者靜態初始化的方式顯式指定DbConfiguration,然後我在Config的EF節點中添加了指定,程式碼片段如下:

 

<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">.......

 

問題解決。

留點東西方便後來踩坑的人。

另,EF+MySql做CodeFirest相性實在不太好(Oracle也差不多),自動遷移時各種水土不服,有條件的公司還是建議上MsSql。

 

EF6與Mysql疑難問題記錄

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.