ASP.NET2.0 ObjectDataSource的使用详解(1)

本文详细介绍了ASP.NET2.0中ObjectDataSource控件的使用方法,包括其与SqlDataSource的区别、属性配置及如何绑定到数据访问层。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

     在李万宝的博客中,对ObjectDataSource的使用进行了详细论述,收藏。。

ASP.NET2.0 ObjectDataSource的使用详解(1)
ASP.NET2.0 ObjectDataSource的使用详解(2)

<st1:chsdate year="1899" month="12" day="30" islunardate="False" isrocdate="False">本系列文章将介绍ObjectDataSource的使用,为了内容的完成性,所以虽然简单,但是还是发到首页,不知道行不行
本系列文章主要参考MSDN,ASP.NET快速入门和ASP.NET的文章整理而成,将由浅入深说明ObjectDataSource的使用,仅供参考,不保证内容100%的争取


1
</st1:chsdate> SqlDataSourceObjectDataSource控件的比较<o:p></o:p>

ASP.NET2.0提供了SqlDataSource数据源控件,后者支持用于指定连接字符串、SQL 语句或存储过程的属性,用以查询或修改数据库。但是,SqlDataSource 控件存在一个问题:该控件的缺点在于它迫使您将用户界面层与业务逻辑层混合在一起。然而随着应用程序规模的扩大,您会越来越感觉到混合多个层的做法是不可取的。 生成严格意义上的多层 Web 应用程序时,您应该具有清晰的用户界面层、业务逻辑层和数据访问层。仅仅由于 SqlDataSource 控件的强制而在用户界面层引用 SQL 语句或存储过程是不可取的。 <o:p></o:p>

SqlDataSourceObjectDataSource的选择,从这某中意义上说,前者适合大多数小规模的个人或业余站点,而对于较大规模的企业级应用程序,在应用程序的呈现页中直接存储 SQL 语句可能很快就会变得无法维护。这些应用程序通常需要用中间层数据访问层或业务组件构成的封装性更好的数据模型。所以使用 ObjectDataSource 控件是一种较为明智和通用的做法。 <o:p></o:p>

<o:p> </o:p>

<st1:chsdate year="1899" month="12" day="30" islunardate="False" isrocdate="False">2</st1:chsdate> ObjectDataSource的概述<o:p></o:p>

ObjectDataSource 控件对象模型类似于 SqlDataSource 控件。ObjectDataSource 公开一个 TypeName 属性(而不是 ConnectionString 属性),该属性指定要实例化来执行数据操作的对象类型(类名)。类似于 SqlDataSource 的命令属性,ObjectDataSource 控件支持诸如 SelectMethodUpdateMethodInsertMethod DeleteMethod 的属性,用于指定要调用来执行这些数据操作的关联类型的方法。本节介绍一些方法,用于构建数据访问层和业务逻辑层组件并通过 ObjectDataSource 控件公开这些组件。 下面是该控件的声明方式:<o:p></o:p>

<asp:ObjectDataSource<o:p></o:p>

    CacheDuration="string|Infinite"    CacheExpirationPolicy="Absolute|Sliding"<o:p></o:p>

    CacheKeyDependency="string"<o:p></o:p>

    ConflictDetection="OverwriteChanges|CompareAllValues"<o:p></o:p>

    ConvertNullToDBNull="True|False"    DataObjectTypeName="string"<o:p></o:p>

    DeleteMethod="string"    EnableCaching="True|False"<o:p></o:p>

    EnablePaging="True|False"    EnableTheming="True|False"<o:p></o:p>

    EnableViewState="True|False"    FilterExpression="string"<o:p></o:p>

    ID="string"    InsertMethod="string"<o:p></o:p>

    MaximumRowsParameterName="string"<o:p></o:p>

    OldValuesParameterFormatString="string"<o:p></o:p>

    OnDataBinding="DataBinding event handler"<o:p></o:p>

    OnDeleted="Deleted event handler"    OnDeleting="Deleting event handler"<o:p></o:p>

    OnDisposed="Disposed event handler"    OnFiltering="Filtering event handler"<o:p></o:p>

    OnInit="Init event handler"    OnInserted="Inserted event handler"<o:p></o:p>

    OnInserting="Inserting event handler"    OnLoad="Load event handler"<o:p></o:p>

    OnObjectCreated="ObjectCreated event handler"<o:p></o:p>

    OnObjectCreating="ObjectCreating event handler"<o:p></o:p>

    OnObjectDisposing="ObjectDisposing event handler"<o:p></o:p>

    OnPreRender="PreRender event handler"    OnSelected="Selected event handler"<o:p></o:p>

    OnSelecting="Selecting event handler"    OnUnload="Unload event handler"<o:p></o:p>

    OnUpdated="Updated event handler"    OnUpdating="Updating event handler"<o:p></o:p>

    runat="server"    SelectCountMethod="string"<o:p></o:p>

    SelectMethod="string"    SortParameterName="string"<o:p></o:p>

    SqlCacheDependency="string"    StartRowIndexParameterName="string"<o:p></o:p>

    TypeName="string"    UpdateMethod="string"<o:p></o:p>

<o:p> </o:p>

><o:p></o:p>

    <DeleteParameters><o:p></o:p>

                <asp:ControlParameter        ControlID="string"<o:p></o:p>

                   ConvertEmptyStringToNull="True|False"<o:p></o:p>

                    DefaultValue="string"<o:p></o:p>

                    Direction="Input|Output|InputOutput|ReturnValue"<o:p></o:p>

                    Name="string"<o:p></o:p>

                    PropertyName="string"<o:p></o:p>

                    Size="integer"<o:p></o:p>

                    Type="Empty|Object|DBNull|Boolean|Char|SByte|<o:p></o:p>

                        Byte|Int16|UInt16|Int32|UInt32|Int64|UInt64|<o:p></o:p>

                        Single|Double|Decimal|DateTime|String"<o:p></o:p>

                /><o:p></o:p>

                <asp:CookieParameter                 CookieName="string"          /><o:p></o:p>

                <asp:FormParameter                   FormField="string"    /><o:p></o:p>

                <asp:Parameter                          Name="string" /><o:p></o:p>

                <asp:ProfileParameter               PropertyName="string"  /><o:p></o:p>

                <asp:QueryStringParameter      QueryStringField="string" /><o:p></o:p>

                <asp:SessionParameter          SessionField="string"  /><o:p></o:p>

        </DeleteParameters><o:p></o:p>

        <FilterParameters>... ...</FilterParameters><o:p></o:p>

        <InsertParameters>... ...</InsertParameters><o:p></o:p>

        <SelectParameters>... ...</SelectParameters><o:p></o:p>

        <UpdateParameters>... ...</UpdateParameters><o:p></o:p>

</asp:ObjectDataSource><o:p></o:p>

<o:p> </o:p>

<st1:chsdate year="1899" month="12" day="30" islunardate="False" isrocdate="False">3</st1:chsdate>绑定到数据访问层<o:p></o:p>

数据访问层组件封装 ADO.NET 代码以通过 SQL 命令查询和修改数据库。它通常提炼创建 ADO.NET 连接和命令的详细信息,并通过可使用适当的参数调用的方法公开这些详细信息。典型的数据访问层组件可按如下方式公开: <o:p></o:p>

public class MyDataBllLayer {  <o:p></o:p>

public DataView GetRecords();  <o:p></o:p>

public int UpdateRecord(int recordID, String recordData); <o:p></o:p>

public int DeleteRecord(int recordID); <o:p></o:p>

public int InsertRecord(int recordID, String recordData);<o:p></o:p>

}<o:p></o:p>

也就是,通常是在业务逻辑访问层定义对数据库里记录的操作,上面就定义了GetRecordsUpdateRecordDeleteRecordInsertRecord四个方法来读取、更新、删除和插入数据库里的数据,这些方法基本上是根据SQL里的SelectUpdateDeleteInsert语句而定义。<o:p></o:p>

和上面方法相对应, ObjectDataSource提供了四个属性来设置该控件引用的数据处理,可以按照如下方式关联到该类型,代码如下<o:p></o:p>

  <asp:ObjectDataSource TypeName="MyDataLayer"   runat="server"<o:p></o:p>

     SelectMethod="GetRecords" <o:p></o:p>

UpdateMethod="UpdateRecord"  <o:p></o:p>

     DeleteMethod="DeleteRecord" <o:p></o:p>

InsertMethod="InsertRecord" <o:p></o:p>

/><o:p></o:p>

    这里的SelectMethon设置为MyDataBllLayer里的GetRecords()方法,在使用时需要注意ObjectDataSource旨在以声明的方式简化数据的开发,所以这里设置SelectMethod的值为GetRecords而不是GetRecords()<o:p></o:p>

同样依次类推,UpdateMethodDeleteMethodInsertMethod分别对应的是UpdateRecord<o:p></o:p>

DeleteRecordInsertRecord方法。<o:p></o:p>

    在上面GetRecords()的定义时,读者可以看到该方法返回的类型是DataView,由于ObjectDataSource将来需要作为绑定控件的数据来源,所以它的返回类型必须如下的返回类型之一:<o:p></o:p>

IenumerableDataTableDataViewDataSet或者Object<o:p></o:p>

     除此以外,ObjectDataSource还有一个重要的属性TypeNameObjectDataSource控件使用反射技术来从来从业务逻辑程序层的类对象调用相应的方法,所以TypeName的属性值就是用来标识该控件工作时使用的类名称,下面通过Simple_ObjectDataSource.aspx来说明ObjectDataSource的基本使用。<o:p></o:p>

1)建立数据业务逻辑层<o:p></o:p>

   为了方装业务逻辑我建立了ProductDAL.cs文件。在该文件里定义了GetProduct方法获取产品列表,UpdateProduct方法更新产品记录,DeleteProduct删除产品记录,为了便于共享,将该文件放置在App_Code目录下,完整代码如1-1<o:p></o:p>

 using System;<o:p></o:p>

using System.Collections.Generic;<o:p></o:p>

using System.ComponentModel;<o:p></o:p>

using System.Configuration;<o:p></o:p>

using System.Data;<o:p></o:p>

using System.Data.Common;<o:p></o:p>

using System.Data.SqlClient;<o:p></o:p>

using System.Web;<o:p></o:p>

<o:p> </o:p>

/// <summary><o:p></o:p>

/// Summary description for ProductBLL<o:p></o:p>

/// </summary><o:p></o:p>

public class ProductDAL<o:p></o:p>

{<o:p></o:p>

    protected int _count = -1;<o:p></o:p>

    public ProductDAL()<o:p></o:p>

    {   }<o:p></o:p>

<o:p> </o:p>

     string   _connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;<o:p></o:p>

<o:p> </o:p>

    public SqlDataReader GetProduct()<o:p></o:p>

    {<o:p></o:p>

        SqlConnection con = new SqlConnection(_connectionString);<o:p></o:p>

        string selectString = "SELECT * FROM Products";<o:p></o:p>

        SqlCommand cmd = new SqlCommand(selectString, con);<o:p></o:p>

        con.Open();<o:p></o:p>

        SqlDataReader dtr = cmd.ExecuteReader(CommandBehavior.CloseConnection);<o:p></o:p>

        return dtr;<o:p></o:p>

         }<o:p></o:p>

<o:p> </o:p>

<o:p> </o:p>

    public void UpdateProduct(int productID, string productName, int categoryID, decimal price, Int16 inStore,string description)<o:p></o:p>

    {<o:p></o:p>

        SqlConnection con = new SqlConnection(_connectionString);<o:p></o:p>

        string updateString = "UPDATE Products set ProductName=@ProductName,CategoryID=@CategoryID,Price=@Price,InStore=@InStore,Description=@Description where ProductID=@ProductID";<o:p></o:p>

        SqlCommand cmd = new SqlCommand(updateString, con);<o:p></o:p>

        cmd.Parameters.AddWithValue("@ProductID",productID);<o:p></o:p>

        cmd.Parameters.AddWithValue("@ProductName",productName);<o:p></o:p>

        cmd.Parameters.AddWithValue("@CategoryID",categoryID);<o:p></o:p>

        cmd.Parameters.AddWithValue("@Price",price);<o:p></o:p>

        cmd.Parameters.AddWithValue("@InStore",inStore);<o:p></o:p>

        cmd.Parameters.AddWithValue("@Description",description);<o:p></o:p>

        con.Open();<o:p></o:p>

        cmd.ExecuteNonQuery();<o:p></o:p>

        con.Close();<o:p></o:p>

    }<o:p></o:p>

<o:p> </o:p>

<o:p> </o:p>

    public   void DeleteProduct(int ProductId)<o:p></o:p>

        {<o:p></o:p>

            SqlConnection con = new SqlConnection(_connectionString);<o:p></o:p>

            string deleteString = "DELETE FROM  Products  WHERE ProductID=@ProductID";<o:p></o:p>

            SqlCommand cmd = new SqlCommand(deleteString, con);<o:p></o:p>

            cmd.Parameters.AddWithValue("@ProductID", ProductId);<o:p></o:p>

            con.Open();<o:p></o:p>

            cmd.ExecuteNonQuery();<o:p></o:p>

            con.Close();<o:p></o:p>

        }<o:p></o:p>

}<o:p></o:p>

          代码1-1 ProductDAL.c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值