首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

MySoft.Data 入門到精通(三):DbSession 配置與自定義實例化

     編輯:關於.NET

DbSession 是資料操作核心,所有 CRUD 皆透過其完成。本文說明兩種實例化方式與自定義擴充技巧。

一、DbSession 實例化兩種方式

1. 組態檔連線字串

// 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");

支援驅動:

  • 內建:SqlServer、Oracle、Access(組件 MySoft.Data.dll)
  • 外掛:MySql、Firebird、SQLite(需額外組件與完整型別名稱 Namespace.Type, Assembly)

2. 動態建立 DbProvider

// 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);

二、自定義 DbSession 擴充類別

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 自動移除,免除手動註釋。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved