DbSession 是資料操作核心,所有 CRUD 皆透過其完成。本文說明兩種實例化方式與自定義擴充技巧。
// Web.config / App.config
<connectionStrings>
<add name="DataExample"
connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa;"
providerName="MySoft.Data.SqlServer9.SqlServer9Provider" />
</connectionStrings>
// 程式碼
var session = new DbSession("DataExample");
支援驅動:
MySoft.Data.dll)Namespace.Type, Assembly)// A. 連線名稱 + ProviderType
var provider = ProviderFactory.CreateDbProvider("DataExample", ProviderType.SqlServer9);
// B. 連線字串 + ProviderType
var provider = ProviderFactory.CreateDbProvider(ProviderType.SqlServer9, "Server=...;Database=...;Uid=...;Pwd=...");
// C. 完全自訂驅動
var provider = ProviderFactory.CreateDbProvider("MyAssembly", "MyNamespace.MyProvider", "connStr");
var session = new DbSession(provider);
public static class DataAccess {
public static readonly DbSession DefaultSession = new DbSession("DataExample");
public static readonly DataExample ExampleSession = new DataExample();
}
public class DataExample : DbSession {
public DataExample() : base("DataExample") {
this.RegisterSqlLogger(log => File.WriteAllText(@"c:\log.txt", log));
}
}
三種呼叫效果相同:
DbSession.Default.Save(user);
DataAccess.DefaultSession.Save(user);
DataAccess.ExampleSession.Save(user); // 額外寫入 SQL 日誌
public DataExample() : base("DataExample") {
#if DEBUG
this.RegisterSqlLogger(log => File.WriteAllText(@"c:\log.txt", log));
#endif
}
DEBUG 模式才註冊,Release 自動移除,免除手動註釋。