作者:陶刚编译
ObjectDataSource控件与SqlDataSource控件的对象模型是类似的。ObjectDataSource没有ConnectionString属性,它暴露了TypeName属性,用于指定需要实例化的执行数据操作的对象类型(类名)。ObjectDataSource控件与SqlDataSource的命令属性相似,也支持SelectMethod、UpdateMethod、InsertMethod和DeleteMethod等属性,用于指明执行这些数据操作的关联类型的方法。本文将解释建立数据访问层和业务逻辑层组件,并通过ObjectDataSource对象展示ASP.NET 2.0数据组件的技术。
绑定到数据访问层
数据访问层组件封装了那些使用SQL命令查询和修改数据库的ADO.NET代码。在典型情况下,它抽象了建立ADO.NET连接和命令的细节信息,暴露了可以通过适当参数调用的方法。典型的数据访问层组件可能暴露了下面一些方法:
public class MyDataLayer { public DataView GetRecords(); public DataView GetRecordsByCategory(String categoryName); public DataView GetRecordByID(int recordID);
public int UpdateRecord(int recordID, String recordData); public int DeleteRecord(int recordID); public int InsertRecord(int recordID, String recordData); } ObjectDataSource可以使用下面的方式来关联到这个类型:
<asp:ObjectDataSource TypeName="MyDataLayer" SelectMethod="GetRecords" UpdateMethod="UpdateRecord" DeleteMethod="DeleteRecord" InsertMethod="InsertRecord" runat="server"/> ObjectDataSource要求对象有非常特殊的设计模式。这些约束都是Web应用程序请求所处的无状态的(stateless)环境引起的。由于在典型情况下,对象的建立和销毁都是为了服务于一个请求,因此通过对象数据源绑定的对象也是无状态的。在默认情况下,ObjectDataSource采用TypeName属性指定的类型的默认的构造函数(不带参数),尽管通过处理ObjectCreating事件来建立一个自定义对象实例,并把它指定给事件参数的ObjectInstance属性,从而实现实例化也是可行的。与SelectMethod属性关联的对象方法可以返回任何对象、Ienumerable列表、集合或数组。在上面的数据访问层示例中,DataView对象实现了IEnumerable接口。我们在下一部分将讨论到,这些方法也可以返回强化类型的集合或对象。
GetProducts() -> ProductCollection GetProductsDataSet() -> DataSet GetProduct (int productId) -> Product Update、Insert和Delete一般把单独的数据项字段作为参数,也可以把带有数据项字段公共属性的集合类对象作为参数。
UpdateProduct (int id, String name, double price, bool inStock) UpdateProduct (Product p) // p.ID, p.Name, p.Price, p.InStock DeleteProduct (int id) 与SqlDataSource的例子类似,传递到Update、Insert和Delete方法的数据项的参数名称或属性必须与SelectMethod返回的字段相同,这样GridView/DetailsView才能自动地进行更新/删除/插入操作。与SqlDataSource类似,ObjectDataSource方法的参数也可以与数据参数对象相关联,使用SelectParameters、FilterParameters、UpdateParameters、DeleteParameters或InsertParameters集合。 下面的例子演示了一个通过数据访问层组件(AuthorsDB)暴露数据的ObjectDataSource控件。这个类型的类文件存放在应用程序的App_Code目录中,在运行时ASP.NET动态地编译它。
<asp:ObjectDataSource ID="ObjectDataSource2" Runat="server" TypeName="AuthorsDB" SelectMethod="GetStates"/>
<asp:ObjectDataSource ID="ObjectDataSource1" Runat="server" TypeName="AuthorsDB" SelectMethod="GetAuthorsByState" UpdateMethod="UpdateAuthor" OldValuesParameterFormatString="{0}"> <SelectParameters> <asp:ControlParameter Name="state" PropertyName="SelectedValue" ControlID="DropDownList1"/> </SelectParameters> </asp:ObjectDataSource>
|