8

.NET 8 之路 - System.Data.SqlClient 轉移 Microsoft.Data.SqlClient 經驗一則

 9 months ago
source link: https://blog.darkthread.net/blog/system-date-sqlclient-migrate-mds/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

System.Data.SqlClient 轉移 Microsoft.Data.SqlClient 經驗一則-黑暗執行緒

前幾天踩到 System.Data.SqlClient 與 .NET 8 不相容的雷,無奈 System.Data.SqlClient 停更已成事實,要繼續往前走,儘早改用 Microsoft.Data.SqlClient 是上策。

咬牙把某個專案的 System.Data.SqlClient 換成 Microsoft.Data.SqlClient,過程還算平和沒動怒 XD,修改處不多,沒遇到刁鑽問題。(轉換順利多少跟專案是用 Dapper 有關,Dapper 封裝了 SqlCommand、SqlParamater、SqlReader 底層操作,而專案也只用到常見的 CRUD 操作)

這篇整理這次轉移涉及的修改,提供有類似需求的同學參考。

  1. 第一步,專案要參照 Microsoft.Data.SqlClient (以下簡稱 MDS),MDS 5.1 在 .NET 8 用到 Guid 欄位會遇到 SqlGuidCaster 無法載入錯誤,現階段可 dotnet add package Microsoft.Data.SqlClient --prerelease 安裝 MDS 5.2.0-preview 解決。
  2. Dapper 在 2.0.4 版移除 System.Data.SqlClient 依賴,同時支援 System.Data.SqlClient 及 MDS 參考,故 Dapper 要升級到 2.0.4 以上。
  3. SqlConnection、SqlCommand、SqlReader、SqlParameter... 等常用型別在 MDS 名稱沒變,故將 using System.Data.SqlClient; 換成 using Microsoft.Data.SqlClient; 即可改用 MDS,幸運的話只改這行就完成切換。
  4. MDS 不再提供 IDbConnection、IDbTransaction 介面,基本上改用 DbConnectionDbTransaction 即可。註:IDb* 介面隸屬 System.Data,Db* 抽象類別隸屬 System.Data.Common,故記得要 using System.Data.Common;
  5. MDS 預設會啟用加密通訊,新版 SQL 大多已支援 TLS 加密,但多半是用自簽憑證,常會遇到 A connection was successfully established with the server, but then an error occured during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted. / 此憑證鏈結是由不受信任的授權單位發出的) 錯誤(參考。我不想為了換 MDS 而修改連線字串,就加了一小段邏輯向前相容。
    void SetConnectionString(string cnStr) 
    {
        var scsb = new SqlConnectionStringBuilder(cnStr);
        // 若連線字串未指定 TrustServerCertificate,設為 true
        if (!cnStr.Contains("TrustServerCertificate", StringComparison.CurrentCultureIgnoreCase)) 
        {
            scsb.TrustServerCertificate = true;
        }
        _cnStr = scsb.ConnectionString;
    }
    

就醬,經過一陣翻修,將 System.Data.SqlClient 換成 Microsoft.Data.SqlClinet,.NET 6 專案終於成功升級成 .NET 8 囉~ (轉圈灑花)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK