Enterprise Library—資料訪問程式塊

來源:互聯網
上載者:User
 

Enterprise Librar—資料訪問程式塊前言

當我們在編寫程式的時候,我們難免要對資料庫進行訪問,在進行資料庫訪問的時候,我們肯定會遇到下面的問題:

1)        重複代碼——Writing (cutting and pasting) the same data access code throughout your data access layer

2)        寫入程式碼——Matching stored procedure parameter definitions with the calling application code

3)        對串連池的擔心——Wondering if your code is properly closing connections

4)        自己寫組件簡化對預存程序的調用——Writing a component to make it simpler to call stored procedures

5)        如何儲存串連串——Wrestling with where/how to store connection string information

當然,這些問題我們自己也是可以解決的,但是資料訪問程式塊給我們提供了這些功能,我們為什麼不用呢?

一、我們的目標

1)        一種簡單有效方法——A simple and efficient way of working with commonly used databases

2)        多種資料庫之間的透明——Transparency when developing for multiple types of databases

3)        邏輯和物理資料庫的“松耦合”——A way to place an indirection between a logical database instance and a physical database instance

4)        簡單的校正方式——An easy way to adjust and validate the database configuration settings

二、Data Access Application Block能夠做什麼

1)        提供最佳實務–Provides access to the most often used features of ADO.NET with applied best practices

2)        改善一致性–Write code that works against multiple database brands(caveats apply!)

3)        改善安全性–Leverages the configuration application block to securely store connection strings

4)        改善易用性–Easily call a stored procedure with one line of code

三、設計Data Access Application Block

資料訪問程式塊要達到的目標:

1)        整合執行資料庫訪問的邏輯

2)        排除常見的代碼錯誤,比如串連失敗

3)        減輕開發人員為常用的資料訪問寫同樣的代碼

4)        減少了一般代碼的書寫

5)        像.NET的資料訪問架構嚮導一樣,為資料訪問整合最好的實踐

6)        儘可能地使資料訪問程式塊的功能適用不同的資料庫

資料訪問程式塊中,各個類之間的關係如下:

 

四、開始實踐

終於知道資料訪問資料區塊是做什麼的了,廢話少說,開始我們的旅程。

1)建立一個Windows或Web應用程式,將Microsoft.Practices.EnterpriseLibrary.Common.dll和Microsoft.Practices.EnterpriseLibrary.Data.dll引用到項目中。

2)把下面的命名空間增加到檔案的頭部using Microsoft.Practices.EnterpriseLibrary.Data

3)看看下面的一段代碼:

 

    Database db = null;

    db = DatabaseFactory.CreateDatabase("QuickStarts Instance");

 

    int count = (int)db.ExecuteScalar(

        CommandType.Text, 

        "SELECT COUNT(*) FROM Customers");

 

    string message = string.Format(

        "There are {0} customers in the database",

        count.ToString());

 

MessageBox.Show(message);

 

(註:db.ExecuteScalar這個命令具有多態性,它和SqlCommand .ExecuteScalar返回的結果一樣。db.ExecuteScalar方法的調用依賴與開啟和關閉定義在設定檔中的資料庫。)

4)再看一段代碼

 

    Database db = null;

    db = DatabaseFactory.CreateDatabase();

 

    DataSet ds = db.ExecuteDataSet(

        CommandType.Text,

        "SELECT * From Customers");

 

dataGrid1.DataSource = ds.Tables[0];

(註:

db.ExecuteDataSet方法依賴與開啟和關閉串連,也返回SQL查詢結果所填充的、可能包含多個表的程式集。這段代碼中,我們沒有指定CreateDatabase方法所建立的資料庫執行個體。其實,在設定檔中有一個預設的資料庫,它就是利用這個預設的資料庫。)

5)再看看預存程序的運用

A.定義一個成員變數,它將在多個過程中使用

private Database _db = DatabaseFactory.CreateDatabase("QuickStarts Instance");

(註:看看這個成員變數的定義,它並不是建立一個資料庫執行個體,只是一個對資料庫的描繪)

B.執行預存程序

 

    using (IDataReader dataReader = _db.ExecuteReader("GetCategories"))

    {

        // Processing code 

        while (dataReader.Read())

        {

            Category item = new Category(

                dataReader.GetInt32(0),

                dataReader.GetString(1),

                dataReader.GetString(2));

            this.cmbCategory.Items.Add(item);

        }

    }

(註:在這裡,你沒有對資料庫的串連做任何的管理,但是,釋放

data reader的傳回值非常重要,這在上述的代碼中完成。當data reader被釋放,DbConnection也被關閉。在Database類中有兩種方法來返回資料集,ExecuteDataSet 和 LoadDataSet。ExecuteDataSet返回一個新建立的資料集,而LoadDataSet是組裝現有的一個。)

6)更新資料庫

 

    // TODO: Use the DataSet to update the Database 

    System.Data.Common.DbCommand insertCommand = null;

    insertCommand = _db.GetStoredProcCommand("HOLAddProduct");

    _db.AddInParameter(insertCommand, "ProductName", 

        DbType.String, "ProductName", DataRowVersion.Current);

    _db.AddInParameter(insertCommand, "CategoryID", 

        DbType.Int32, "CategoryID", DataRowVersion.Current);

    _db.AddInParameter(insertCommand, "UnitPrice", 

        DbType.Currency, "UnitPrice", DataRowVersion.Current);

 

    System.Data.Common.DbCommand deleteCommand = null;

    deleteCommand = _db.GetStoredProcCommand("HOLDeleteProduct");

    _db.AddInParameter(deleteCommand, "ProductID",

        DbType.Int32, "ProductID", DataRowVersion.Current);

    _db.AddInParameter(deleteCommand, "LastUpdate", 

        DbType.DateTime, "LastUpdate", DataRowVersion.Original);

 

    System.Data.Common.DbCommand updateCommand = null;

    updateCommand = _db.GetStoredProcCommand("HOLUpdateProduct");

    _db.AddInParameter(updateCommand, "ProductID", 

        DbType.Int32, "ProductID", DataRowVersion.Current);

    _db.AddInParameter(updateCommand, "ProductName", 

        DbType.String, "ProductName", DataRowVersion.Current);

    _db.AddInParameter(updateCommand, "CategoryID", 

        DbType.Int32, "CategoryID", DataRowVersion.Current);

    _db.AddInParameter(updateCommand, "UnitPrice", 

        DbType.Currency, "UnitPrice", DataRowVersion.Current);

    _db.AddInParameter(updateCommand, "LastUpdate", 

        DbType.DateTime, "LastUpdate", DataRowVersion.Current);

 

    int rowsAffected = _db.UpdateDataSet(

        this.dsProducts,

        "Products",

        insertCommand,

        updateCommand,

        deleteCommand,

        UpdateBehavior.Standard);

(註:當我們更新資料庫時,我們需要人工地建立預存程序的參數,需要知道

DataTable的列和預存程序參數的映射。在這裡UpdateDataSet方法,通過設定,可以擷取資料流執行所有的更新事務。)

7)利用Enterprise Library Configuration來設定項目的設定檔

A.開啟設定檔

如果你有定義在machine.config檔案串連節,你會發現Enterprise Library Configuration工具會自動建立Data Access Application Block。

 

如果沒有,你也可以自己建立一個,如下:

 


B.選擇 the Data Access Application Block | Connection Strings | Connection String node. Change the Name property to QuickStarts Instance.

 


C.Select the Database node for this connection string. Change the Value property on the right hand side to EntLibQuickStarts.

 


D.選擇 the Server node, and set its Value to "(local)\SQLEXPRESS".

 


E.Select the Data Access Application Block node. Set the DefaultDatabase property is to the QuickStarts Instance. Then, save it.

 

參考資料

Download Enterprise Library and related resources from:

http://msdn.microsoft.com/practices

http://msdn.microsoft.com/library/?url=/library/en-us/dnpag2/html/EntLib2.asp

Join theEnterprise Library Community at:

http://practices.gotdotnet.com/projects/entlib

Read blogs from the Enterprise Library team at:

http://msdn.microsoft.com/practices/Comm/EntLibBlogs/ 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.