為什么說這是一個可能出現的bug,因為這個bug很奇怪我試了創建了很多次項目去執行相同的代碼卻只有一個會先這種情況。
SqlSugarCore版本:5.0.2.8
程序版本:.net5--winform程序。
錯誤
SqlSugar.SqlSugarException:“English Message : Connection open error . The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
Chinese Message : 連接數據庫過程中發生錯誤,檢查服務器是否正常連接字符串是否正確,實在找不到原因請先Google錯誤信息:The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception..”
代碼
var connectionString = new SqliteConnectionStringBuilder() { //Mode = SqliteOpenMode.ReadWriteCreate, DataSource = @"d:\refund.db" }.ToString(); SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = connectionString,//連接符字串 DbType = SqlSugar.DbType.Sqlite, IsAutoCloseConnection = true, ConfigId = "sqlite", IsShardSameThread = true }); db.Ado.ExecuteCommand("select 1");
思路
在出現這個錯誤之后我第一次檢查的就是sqlite的連接字符串。在對比了很多次之后我排除了是連接字符串的問題。
因為我已相同的連接字符串另外一個.net5的程序中跑的時候是沒有問題的。
因為SqlSugarCore的sqlite依賴包是Microsoft.Data.Sqlite。
我試着用原生的SqliteConnection去嘗試連接數據庫。
代碼:
var connectionString = new SqliteConnectionStringBuilder() { //Mode = SqliteOpenMode.ReadWriteCreate, DataSource = @"d:\refund.db" }.ToString(); using (SqliteConnection connection = new SqliteConnection(connectionString)) { connection.Open(); SqliteCommand command = new SqliteCommand("select 1", connection); var reader = command.ExecuteReader(); }
出現錯誤。
錯誤1:
The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.”
錯誤2
MissingMethodException: Method not found: 'Int32 SQLitePCL.ISQLite3Provider.sqlite3_win32_set_directory(Int32, System.String)'.
重點是錯誤2,然后去網上找了一圈也沒有解決方案,然后群友說可能是程序包版本問題。
SQLitePCLRaw.bundle_green 根據錯誤來看可能是這個依賴包有問題。
我只得重新安裝這個包的最新版本。
然后運行程序,發現可以連接字符串。
但是這個依賴包在安裝SqlSugarCore的時候已經安裝了,安裝的也是最新的包,但是卻會報錯,真是百思不得其解啊。
結語
遇到問題還是得要有正確的思路要不然真的難。