天天看點

NBearLite使用入門

NBearLite是NBearV4的幾個核心元件之一,也是目前NBearV3中ORM部分的查詢文法的核心。NBearLite本身并不是一個完整的ORM解決方案,配合目前Teddy正常開發的NBearMapping元件使用(某個中間元件過渡),組成一套完整強大的ORM解決方案。NBearLite的目标是提供一種SQL語句和存儲過程透明的友善快捷,面向對象化的資料庫操作,專門負責SQL語句生成,資料庫連接配接管理,事務管理,參數管理,提供各種查詢接口。

在NBearV3中希望從一個表中根據條件查詢出資料對象,可以使用如下對象查詢文法:

1 Product[] products = gateway.From<Product>().Where((Product._.UnitsInStock <= Product._.ReorderLevel

&& !(Product._.Discontinued == true)) || Product._.UnitPrice < 10m).ToArray<Product>;

1 Product[] products = gateway.From<Product>().Where((Product._.UnitsInStock <= Product._.ReorderLevel && !(Product._.Discontinued == true)) || Product._.UnitPrice < 10m).ToArray<Product>;

這裡,從對象邏輯文法到SQL語句的生成,再到結果集映射,NBearV3的Gateway對象一手包辦。

ds = db.Select(Northwind.Categories, Northwind.Categories.CategoryName).Where(Northwind.Categories.CategoryID > 0).ToDataSet(); 

在NBearLite中,繼承保留了NBearV3的對象查詢文法,專職負責查詢。而且隻保留了ToDataReader,ToDataSet,ToScalar等傳回ADO.NET原生資料對象的接口,與實體沒有直接的聯系。如下代碼取自,NBearLite DatabaseTest:

ds = db.Select(Northwind.Categories, Northwind.Categories.CategoryName).

Where(Northwind.Categories.CategoryID > 0).ToDataSet(); 

在NBearLite中,資料接口由Gateway變成了Database,所有的資料庫操作都是通過Database所提供的接口來完成。在NBearLite也不需要定義和建立與資料庫字段相關的實體類(不需要映射),那麼如何實作對象化的資料庫操作呢?在NBearLite中,提供了一個中NBearLite.QueryColumnsGenerator的代碼生成工具,故名思意,就是用于生成查詢字段描述代碼的工具。該工具可以生成整個資料庫,包括包,視圖的字段描述定義,存儲過程的函數式調用的包裝代碼。 

字段描述定義,可以參看NBearV3中,實體類的@__Columns内聯類的定義,實際工具生成的就是這段代碼。存儲過程的包裝代碼确實有點創意,如下:  

public static System.Data.DataSet CustOrderHist(NBearLite.Database db, out int RETURN_VALUE, string CustomerID)

    {

        if ((db == null))

        {

            throw new System.ArgumentNullException("db", "Parameter: db could not be null!");

        }

        NBearLite.StoredProcedureSection spSection = db.StoredProcedure("CustOrderHist");

        System.Collections.Generic.Dictionary<string, object> outValues;

        spSection.SetReturnParameter("RETURN_VALUE", System.Data.DbType.Int32, 0);

        spSection.AddInputParameter("CustomerID", System.Data.DbType.StringFixedLength, CustomerID);

        System.Data.DataSet ds = spSection.ToDataSet(out outValues);

        RETURN_VALUE = ((int)(outValues["RETURN_VALUE"]));

        return ds;

    }

這樣我們調用該存儲過程就可以直接使用函數傳參和獲得傳回值,完全可以避免煩雜的ADO.NET對象操作,便于調用和維護。對資料庫中的每個存儲過程,NBearLite都會生成一個與之對應的調用函數。

現在,參照NBearLite的Test用例,簡單介紹一下NBearLite該如何使用。首先要建立一個Database對象,Database db = new Database("Northwind");該構造函數可接受多種重載,這種是最常用的重載方式,”Northwind”是在application config 中定義好的一個資料庫連接配接串名稱。

<add name="Northwind" connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa" />

該配置節的providerName屬性名可以用于指定使用哪種NBearLite Db Provider,如下配置節就表示,客戶系統希望使用postgresql資料庫:

<add name="Postgres" connectionString="User ID=postgres;Password=sasa;Host=localhost;Port=5432;Database=postgres;

Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;" providerName="postgresql" />

Database對象生成後,就所有的資料庫操作都是通過它來完成的,其中Northwind類就是由NBearLite.QueryColumnsGenerator生成的資料庫描述類: 

1. 往資料庫插入一條隻有一個CategoryName字段值的記錄

db.Insert(Northwind.Categories).AddColumn(Northwind.Categories.CategoryName, "test1").Execute()

2. 根據條件更新字段值

db.Update(Northwind.Categories).AddColumn(Northwind.Categories.CategoryName, "test1").

Where(Northwind.Categories.CategoryName == "test1").Execute()

3. 根據條件删除記錄

db.Delete(Northwind.Categories).Where(Northwind.Categories.CategoryName == "test111").Execute()

4. 查詢記錄

a) 簡單查詢

DataSet ds = db.Select(Northwind.Categories).ToDataSet();

//查詢Northwind資料庫的Categories表中的所有記錄。

ds = db.Select(Northwind.Categories, Northwind.Categories.CategoryName).

Where(Northwind.Categories.CategoryID > 0).ToDataSet();

//查詢傳回Categories中CategoryID大于0的CategoryName列記錄。

b) 複雜查詢

db.Select(Northwind.Categories, Northwind.Categories.CategoryName).

GroupBy(Northwind.Categories.CategoryName).OrderBy(Northwind.Categories.CategoryName.Desc).

SetSelectRange(2, 2, Northwind.Categories.CategoryName).ToDataSet()

//根據CategoryName分組,排序,并傳回從第3行開始的前兩條資料。

db.Select(Northwind.Categories, Northwind.Categories.__Alias("CategoriesAlias").CategoryName).

Join(Northwind.Categories, "CategoriesAlias", Northwind.Categories.CategoryID ==

Northwind.Categories.__Alias("CategoriesAlias").CategoryID).

SetSelectRange(2, 2, Northwind.Categories.CategoryID).Where(Northwind.Categories.CategoryName.Length > 0 &&

Northwind.Categories.__Alias("CategoriesAlias").Description != null).

ToDataSet(); 

//上面的語句示範了如何進行表之間的關聯查詢

5. 調用存儲過程

Northwind.SalesbyYear(db, out ret, new DateTime(1800, 9, 9), DateTime.Now);

NBearLite本身并不需要任何的外部配置的支援,對象化的查詢文法會自動生成SQL語句的同時,也提供了多種資料庫透明的可能。目前NBearLite中已實作的Db Provider包括:SqlServer(2000/2005),Oracle,MsAccess,MySql,PostgreSql,Sqlite。大部分都是我沒有使用過的。L

最後一點,關于生成的SQL語句儲存起來便于跟蹤的問題。那天在MSN群裡有一位朋友在問如何使用Log委托的問題,到最後愣是沒讓他明白。在NBear中,所有的日志記錄方式都是一樣的,也很簡單。如下定義一個相同原型的函數(靜态函數):

 public static void OnLog(string sql)

    {

    } 

函數名可以不一樣,參sql就是生成的SQL語句,在該函數中,我們可以決定是将該參數儲存到檔案中,還是顯示出來。

接下來将該函數指派給db.OnLog屬性成員

db.OnLog += OnLog;

+= 是委托代理的使用方式。就這樣,就可以實作SQL語句的跟蹤了。如果對委托代理還不了解的朋友,建議可以去了解一下相關的知識。

文中提到的相關代碼和使用示例,可以到NBearLite的Test工程中得到。NBearLite的源碼可以從這裡下載下傳.

完。

原文作者:阿不

相關文章:

NBearLite入門二