objectdatasource的使用

1 SqlDataSource和ObjectDataSource控件的比較
ASP.NET2.0提供了 SqlDataSource 數據源控件,後者支持用於指定鏈接字符串、 SQL 語句或存儲過程的屬性,用以查詢或修改數據庫。可是, SqlDataSource 控件存在一個問題:該控件的缺點在於它迫使您將用戶界面層與業務邏輯層混合在一塊兒。然而隨着應用程序規模的擴大,您會愈來愈感受到混合多個層的作法是不可取的。 生成嚴格意義上的多層 Web 應用程序時,您應該具備清晰的用戶界面層、業務邏輯層和數據訪問層。僅僅因爲 SqlDataSource 控件的強制而在用戶界面層引用 SQL 語句或存儲過程是不可取的。
SqlDataSource ObjectDataSource 的選擇,從這某中意義上說,前者適合大多數小規模的我的或業餘站點,而對於較大規模的企業級應用程序,在應用程序的呈現頁中直接存儲 SQL 語句可能很快就會變得沒法維護。這些應用程序一般須要用中間層數據訪問層或業務組件構成的封裝性更好的數據模型。因此使用 ObjectDataSource 控件是一種較爲明智和通用的作法。
 
2 ObjectDataSource 的概述
ObjectDataSource 控件對象模型相似於 SqlDataSource 控件。 ObjectDataSource 公開一個 TypeName 屬性(而不是 ConnectionString 屬性),該屬性指定要實例化來執行數據操做的對象類型(類名)。相似於 SqlDataSource 的命令屬性, ObjectDataSource 控件支持諸如 SelectMethod UpdateMethod InsertMethod DeleteMethod 的屬性,用於指定要調用來執行這些數據操做的關聯類型的方法。本節介紹一些方法,用於構建數據訪問層和業務邏輯層組件並經過 ObjectDataSource 控件公開這些組件。 下面是該控件的聲明方式:
<asp:ObjectDataSource
    CacheDuration="string|Infinite"    CacheExpirationPolicy="Absolute|Sliding"
    CacheKeyDependency="string"
    ConflictDetection="OverwriteChanges|CompareAllValues"
    ConvertNullToDBNull="True|False"    DataObjectTypeName="string"
    DeleteMethod="string"    EnableCaching="True|False"
    EnablePaging="True|False"    EnableTheming="True|False"
    EnableViewState="True|False"    FilterExpression="string"
    ID="string"    InsertMethod="string"
    MaximumRowsParameterName="string"
    OldValuesParameterFormatString="string"
    OnDataBinding="DataBinding event handler"
    OnDeleted="Deleted event handler"    OnDeleting="Deleting event handler"
    OnDisposed="Disposed event handler"    OnFiltering="Filtering event handler"
    OnInit="Init event handler"    OnInserted="Inserted event handler"
    OnInserting="Inserting event handler"    OnLoad="Load event handler"
    OnObjectCreated="ObjectCreated event handler"
    OnObjectCreating="ObjectCreating event handler"
    OnObjectDisposing="ObjectDisposing event handler"
    OnPreRender="PreRender event handler"    OnSelected="Selected event handler"
    OnSelecting="Selecting event handler"    OnUnload="Unload event handler"
    OnUpdated="Updated event handler"    OnUpdating="Updating event handler"
    runat="server"    SelectCountMethod="string"
    SelectMethod="string"    SortParameterName="string"
    SqlCacheDependency="string"    StartRowIndexParameterName="string"
    TypeName="string"    UpdateMethod="string"
 
>
    <DeleteParameters>
                <asp:ControlParameter        ControlID="string"
                   ConvertEmptyStringToNull="True|False"
                    DefaultValue="string"
                    Direction="Input|Output|InputOutput|ReturnValue"
                    Name="string"
                    PropertyName="string"
                    Size="integer"
                    Type="Empty|Object|DBNull|Boolean|Char|SByte|
                        Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|
                        Single|Double|Decimal|DateTime|String"
                />
                <asp:CookieParameter                 CookieName="string"          />
                <asp:FormParameter                   FormField="string"    />
                <asp:Parameter                          Name="string" />
                <asp:ProfileParameter               PropertyName="string"  />
                <asp:QueryStringParameter      QueryStringField="string" />
                <asp:SessionParameter          SessionField="string"  />
        </DeleteParameters>
        <FilterParameters>... ...</FilterParameters>
        <InsertParameters>... ...</InsertParameters>
        <SelectParameters>... ...</SelectParameters>
        <UpdateParameters>... ...</UpdateParameters>
</asp:ObjectDataSource>
 
3 綁定到數據訪問層
數據訪問層組件封裝 ADO.NET 代碼以經過 SQL 命令查詢和修改數據庫。它一般提煉建立 ADO.NET 鏈接和命令的詳細信息,並經過可以使用適當的參數調用的方法公開這些詳細信息。典型的數據訪問層組件可按以下方式公開:
public class MyDataBllLayer { 
public DataView GetRecords(); 
public int UpdateRecord(int recordID, String recordData);
public int DeleteRecord(int recordID);
public int InsertRecord(int recordID, String recordData);
}
也就是 , 一般是在業務邏輯訪問層定義對數據庫裏記錄的操做,上面就定義了 GetRecords UpdateRecord DeleteRecord InsertRecord 四個方法來讀取、更新、刪除和插入數據庫裏的數據,這些方法基本上是根據 SQL 裏的 Select Update Delete Insert 語句而定義。
和上面方法相對應, ObjectDataSource 提供了四個屬性來設置該控件引用的數據處理,能夠按照以下方式關聯到該類型,代碼以下
  <asp:ObjectDataSource TypeName="MyDataLayer"   runat="server"
     SelectMethod="GetRecords"
UpdateMethod="UpdateRecord" 
     DeleteMethod="DeleteRecord"
InsertMethod="InsertRecord"
/>
    這裏的 SelectMethon 設置爲 MyDataBllLayer 裏的 GetRecords() 方法,在使用時須要注意 ObjectDataSource 旨在以聲明的方式簡化數據的開發,因此這裏設置 SelectMethod 的值爲 GetRecords 而不是 GetRecords()
一樣依次類推, UpdateMethod DeleteMethod InsertMethod 分別對應的是 UpdateRecord
DeleteRecord InsertRecord 方法。
    在上面 GetRecords ()的定義時,讀者能夠看到該方法返回的類型是 DataView ,因爲 ObjectDataSource 未來須要做爲綁定控件的數據來源,因此它的返回類型必須以下的返回類型之一:
Ienumerable DataTable DataView DataSet 或者 Object
     除此之外, ObjectDataSource 還有一個重要的屬性 TypeName ObjectDataSource 控件使用反射技術來歷來從業務邏輯程序層的類對象調用相應的方法,因此 TypeName 的屬性值就是用來標識該控件工做時使用的類名稱,下面經過 Simple_ObjectDataSource.aspx 來講明 ObjectDataSource 的基本使用。
1 )創建數據業務邏輯層
   爲了方裝業務邏輯我創建了 ProductDAL.cs 文件。在該文件裏定義了 GetProduct 方法獲取產品列表, UpdateProduct 方法更新產品記錄, DeleteProduct 刪除產品記錄,爲了便於共享,將該文件放置在 App_Code 目錄下,完整代碼如1 -1
 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
 
/// <summary>
/// Summary description for ProductBLL
/// </summary>
public class ProductDAL
{
    protected int _count = -1;
    public ProductDAL()
    {   }
 
     string   _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 
    public SqlDataReader GetProduct()
    {
        SqlConnection con = new SqlConnection(_connectionString);
        string selectString = "SELECT * FROM Products";
        SqlCommand cmd = new SqlCommand(selectString, con);
        con.Open();
        SqlDataReader dtr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return dtr;
         }
 
 
    public void UpdateProduct(int productID, string productName, int categoryID, decimal price, Int16 inStore,string description)
    {
        SqlConnection con = new SqlConnection(_connectionString);
        string updateString = "UPDATE Products set ProductName=@ProductName,CategoryID=@CategoryID,Price=@Price,InStore=@InStore,Description=@Description where ProductID=@ProductID";
        SqlCommand cmd = new SqlCommand(updateString, con);
        cmd.Parameters.AddWithValue("@ProductID",productID);
        cmd.Parameters.AddWithValue("@ProductName",productName);
        cmd.Parameters.AddWithValue("@CategoryID",categoryID);
        cmd.Parameters.AddWithValue("@Price",price);
        cmd.Parameters.AddWithValue("@InStore",inStore);
        cmd.Parameters.AddWithValue("@Description",description);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
 
 
    public   void DeleteProduct(int ProductId)
        {
            SqlConnection con = new SqlConnection(_connectionString);
            string deleteString = "DELETE FROM  Products  WHERE ProductID=@ProductID";
            SqlCommand cmd = new SqlCommand(deleteString, con);
            cmd.Parameters.AddWithValue("@ProductID", ProductId);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
}
          代碼1 -1 ProductDAL.cs 源文件
  
 
2 )創建表示層
  創建一個頁面 Simple_ObjectDataSource.aspx 而後將 ObjectDataSource 控件託方到 Web 窗體創,使用默認的 ID Visual Stduio.NET2005 爲咱們創建業務邏輯提供了強大的支持。選中 ObjectDataSource1 ,在其智能配置裏選擇配置數據源,彈出配置嚮導如圖 2-1

                                     圖
2-1ObjectDataSource 配置嚮導
 
  此時系統會枚舉已經存在的類,選擇 ProductDAL ,單擊「 Next 」,進入「 Define Data Methods 」頁面如圖 2-2 。在此頁面須要單獨設置 Select Update 、和 Delete 分別以下圖


2-30
設置 Select 屬性對應的方法 GetProduct


2-31
設置 Update 屬性對應的方法 UpdateProduct


2-32 設置 Delete 屬性對應的方法 DeleteProduct
 
經過上面的設置系統自動生成以下代碼以下
  <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="DeleteProduct"
            SelectMethod="GetProduct" TypeName="ProductDAL" UpdateMethod="UpdateProduct">
            <DeleteParameters>
                <asp:Parameter Name="ProductId" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="productID" Type="Int32" />
                <asp:Parameter Name="productName" Type="String" />
                <asp:Parameter Name="categoryID" Type="Int32" />
                <asp:Parameter Name="price" Type="Decimal" />
                <asp:Parameter Name="inStore" Type="Int16" />
                <asp:Parameter Name="description" Type="String" />
            </UpdateParameters>
        </asp:ObjectDataSource>
         代碼 2-11 Simple_ObjectDataSource.aspx 部分源代碼
2-33 顯示了運行結果,此時咱們能夠編輯或者刪除現有的產品記錄。


       
2-33 Simple_ObjectDataSource.aspx 運行結果
 
注意:若是可以進行編輯、刪除,你須要將GridViewDataKeyNames設置爲數據庫裏的主鍵名。具體後面會說明。
相關文章
相關標籤/搜索