DbSession.Default 會自動抓取 connectionStrings 最後一個節點,實務上專案常有多資料庫,建議以靜態類別集中管理:
public static class Db
{
// 每個資料庫一個靜態唯讀 DbSession
public static readonly DbSession Northwind = new DbSession("NorthwindConnectionString");
public static readonly DbSession ErpDb = new DbSession("ErpConnectionString");
// 靜態建構函式:註冊 SQL 記錄事件(僅執行一次)
static Db()
{
Northwind.RegisterSqlLogger(sql =>
File.AppendAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sqllog.txt"), sql));
ErpDb.RegisterSqlLogger(sql =>
Hxj.Common.Log4net.Debug(sql)); // 生產環境建議用 log4net
}
}
// 程式碼中統一透過 Db.Northwind / Db.ErpDb 存取
var products = Db.Northwind.From().ToList();
var orders = Db.ErpDb.From().Where(...).ToList();
Db.Northwind 一眼看出操作哪個資料庫,避免 Default 切換連線字串順序導致的 Bug。Db 類別,易於代碼審查與維護。readonly 確保實例只建立一次,無鎖、無鎖競爭。// 簡單檔案記錄(開發測試用,注意檔案無限增長)
Northwind.RegisterSqlLogger(sql => File.AppendAllText("sqllog.txt", sql + Environment.NewLine));
// 生產級:log4net 非同步寫入、滾動檔案、等級過濾
Northwind.RegisterSqlLogger(sql => Hxj.Common.Log4net.Debug(sql));
// 條件記錄:只記錄超過 100ms 的慢查詢
Northwind.RegisterSqlLogger((sql, elapsedMs) => {
if (elapsedMs > 100) Log4net.Warn($"Slow SQL ({elapsedMs}ms): {sql}");
});
採用此模式,專案資料庫存取層結構清晰、可追蹤、易擴展,是 Hxj.Data 實務專案的標準作法。