asp.net 2.0 ObjectDataSource Control

Source: Internet
Author: User
Tags expression implement include insert interface object model sort visual studio
Asp.net|object| Control

The ObjectDataSource control is similar to the SqlDataSource control's object model. ObjectDataSource has no ConnectionString property, exposing the TypeName property to specify the object type (class name) to perform the data operation that needs to be instantiated. The ObjectDataSource control is similar to the SqlDataSource Command property, and also supports properties such as SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod. A method that indicates the type of association to perform these data operations. This article explains the techniques for building the data access layer and business logic layer components and displaying the ASP.net 2.0 data components through ObjectDataSource objects.

   binding to the data access layer

The data access layer component encapsulates the Ado.net code that queries and modifies the database using SQL commands. In a typical case, it abstracts the details of establishing ado.net connections and commands, exposing methods that can be invoked through the appropriate parameters. A typical data access layer component might expose some of the following methods:

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 can be associated with this type in the following ways:

<asp:objectdatasource typename= "Mydatalayer" selectmethod= "Getrecords" updatemethod= "UpdateRecord"
Deletemethod= "DeleteRecord" insertmethod= "Insertrecord" runat= "Server"/>
ObjectDataSource requires objects to have a very special design pattern. These constraints are caused by a stateless (stateless) environment where Web application requests are made. Because in typical cases, objects are created and destroyed to serve a request, objects bound by an object data source are stateless. By default, ObjectDataSource uses the default constructor of the type specified by the TypeName property (without parameters), although a custom object instance is established by handling the ObjectCreating event. and assign it to the ObjectInstance attribute of the event parameter, so it is feasible to implement the instantiation. The object method associated with the SelectMethod property can return any object, IEnumerable list, collection, or array. In the above example of the data access layer, the DataView object implements the IEnumerable interface. As we'll discuss in the next section, these methods can also return a collection or object of the hardening type.

GetProducts ()-> Productcollection
Getproductsdataset ()-> DataSet
getproduct (int productId)-> Product
Update, insert, and delete generally take a separate data item field as a parameter, or a collection class object with a public property of a data item field as a parameter.

updateproduct (int id, String name, double price, bool instock)
UpdateProduct (Product p)//P.id, P.name, P.price, P.instock
deleteproduct (int id)
Similar to the SqlDataSource example, the parameter name or property of a data item passed to the update, insert, and Delete methods must be the same as the field returned by SelectMethod, so that gridview/ DetailsView for automatic Update/delete/insert operations. Like SqlDataSource, parameters of the ObjectDataSource method can also be associated with data parameter objects, using SelectParameters, FilterParameters, UpdateParameters, DeleteParameters or InsertParameters collection.
The following example shows a ObjectDataSource control that exposes data through the data Access Layer component (AUTHORSDB). This type of class file is stored in the App_Code directory of the application and dynamically compiled at runtime 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>

   binding to the business logic layer

With regard to the data access layer, we also need to focus on the fact that because SelectMethod returns the result of executing the query as a data view, it still exposes the outline of the underlying database to the display page. Also, there is no business rule at the data Access layer; it simply executes the query and returns the results. If you need to isolate the display from the database outline and introduce business rules or validation procedures, you typically need to wrap the data access layer into the business logic layer.

The business logic layer, like the Dal, exposes ObjectDataSource to a stateless method for binding controls on a Web page. However, it generally does not return ado.net results directly, but instead returns objects of the hardening type that represent the business entities used by the application. This separation of the display layer from the underlying data storage outline makes it easier for us to maintain the data access portion of the site individually without modifying the pages that use the data. With the right middle tier, you can completely modify the underlying data storage outline without updating the standalone pages in your application.

The following is an example of a business logic layer.

public class Mybusinesslayer {

Public recordcollection getrecords ();
Public recordcollection getrecordsbycategory (String CategoryName);
Public recordcollection Getrecordbyid (int recordid);
Public String getrecordname (int recordid);
Public Object getrecorddata (int recordid);

public int UpdateRecord (record R);
public int DeleteRecord (record R);
public int Insertrecord (record R);

public int Updaterecorddata (int ID, String Data);
public int updaterecordname (int ID, String Name);
}

public class Record {
public int ID {get; set;}
Public String Name {get; set;}
Public Object Data {get; set;}
}
The main difference between the business logic layer and the data access layer is that the business logic layer returns a collection of record objects of the hardening type (recordcollection) rather than a data view. It also allows us to update, insert, and delete this record object as a parameter. The ObjectDataSource DataObjectTypeName property allows you to configure ObjectDataSource to pass a type instead of a field value. In the method implementation of the business logic layer, you can include custom logic for validating business rules. For example, you can make sure that only the record in the "Check in" category is updated, or that only administrators can insert new records. You can also include validation logic to ensure that the data types and values passed in as parameters are correct before inserting or modifying the data in the database. Note that the validation rule in the business logic layer is not a substitute for the display layer's input validation, which directs end users to enter the correct value before submitting an update.

The following example shows a simple business logic layer called authorscomponent. Inside it, BLL actually performs database operations through the DAL call. For simplicity, BLL does not contain any business rules or validations, although it may be a realistic application. We also note that this example does not return a record of the hardening type by writing a custom collection class, but instead takes advantage of the. NET Framework component 2.0, a new language feature called "Paradigm (generics)" To create a collection of author objects. Using an enhanced type collection allows ObjectDataSource to derive the outline of a business object at design time (in Visual Studio and other tools).

<asp:dropdownlist id= "DropDownList1" runat= "Server" datasourceid= "ObjectDataSource2" autopostback= "True"/>
<asp:objectdatasource id= "ObjectDataSource2" runat= "Server" Typename= "authorscomponent" selectmethod= "getstates"/>
<asp:gridview id= "GridView1" runat= "Server" datasourceid= "ObjectDataSource1" autogeneratecolumns= "False" Allowpaging= "true" allowsorting= "true"
......
</asp:GridView>
<asp:objectdatasource id= "ObjectDataSource1" runat= "typename=" AuthorsComponent "selectmethod=" Getauthorsbystate "updatemethod=" Updateauthor "dataobjecttypename=" Author "sortparametername=" SortExpression "
......
</asp:ObjectDataSource>
The following diagram shows the interaction between the GridView, ObjectDataSource, and business logic tiers. ObjectDataSource is configured to call the Getcontacts method of the Contactslist type, returning a collection of contact objects. The GridView lists the contact object and binds directly to the type's properties (ID, Name) to generate the column. Note that SelectMethod can return a contact object's IEnumerable interface or return a single Contact object. If not implemented Ienumerable,objectdatasource will encapsulate the results returned by SelectMethod into IEnumerable.

The ObjectDataSource control is similar to SqlDataSource, and it also supports sorting when SelectMethod returns a dataset, Data View, or Datasheet object. ObjectDataSource depends on the data view. In this example, the Sort property performs a sorting operation. ObjectDataSource also supports custom sorting in the SelectMethod implementation, which is useful if the method does not return datasets, data Views, and datasheets. You can implement custom sorting by setting the SortParameterName property to the name of the method parameter that accepts sortexpression from the data source. When calling SelectMethod, ObjectDataSource will pass this expression to your method, and you can use this expression to implement your own sorting logic. The previous example demonstrates customizing a sort implementation in the AuthorsComponent class.

ObjectDataSource also supports custom paging functionality in the SelectMethod implementation. You need to use the StartRowIndexParameterName, MaximumRowsParameterName, and SelectCountMethod properties to set it.
Binding to a Visual Studio dataset

The operation of binding data access layers can be tedious, because in different methods of the DAL, the ado.net Code of the SQL statement or stored procedure is executed in the same or similar way. Although you can use the above techniques to write your own dal,visual studio with custom ado.net code, it provides a convenient way to generate a data access layer based on a simple wizard. In this case, the data access layer is the data set object of the hardening type. The dataset contains the TableAdapter type, which exposes the method used to return the data table object of the hardening type. These methods are suitable for direct binding to ObjectDataSource, or for invocation in the business Logic layer component.

To add a dataset to a Visual Studio object, you need to right-click Solution Explorer and select Add New Item, then select the DataSet item type. Visual Studio adds a dataset.xsd file to the App_Code directory and opens the DataSet Designer, loading the TableAdapter wizard. You can follow the TableAdapter wizard, specify the SQL statements or stored procedures in the database, and then enter the name of the method associated with these queries/commands on the last page of the wizard.

TableAdapter can expose two methods: The Fill method fills an existing dataset, and the Get method returns a data table object that has already been populated. The former is more suitable for Windows clients (the dataset is stored in memory during the life cycle of the application), and the latter is suitable for ObjectDataSource. The TableAdapter Wizard also automatically generates update, insert, and Delete methods for the SQL selection statements you provide (you need to select a primary key). After you configure the wizard, Visual Studio adds a new data table and TableAdapter type to the DataSet Designer.

TableAdapter describes the selection, update, insert, or delete operations on the outline and outline of a single result set. You can add multiple TableAdapter to a dataset by right-clicking in the DataSet Designer. You can also add additional queries to TableAdapter by right-clicking the TableAdapter box in the designer (if they return the same outline). For example, your TableAdapter may contain both the getauthors () and Getauthorsbyid (int id) methods, but if you are adding a gettitles () method, you may need to add a new TableAdapter. The following illustration shows the DataSet Designer with multiple TableAdapter added:

Once you have finished designing the dataset, you can save the Dataset.xsd file (which causes the type to be compiled in the background by the designer for use by the page). You can see these types of code that are exposed to the page:

protected void Page_Load (object sender, EventArgs e)
{
Datasettableadapters.photostableadapter adapter = new Datasettableadapters.photostableadapter ();
Adapter. Getphotosforalbum (0);
}
However, you do not need to invoke these methods from your own code. You can bind ObjectDataSource to these methods:

<asp:objectdatasource id= "ObjectDataSource1" runat= "Server"
Typename= "Datasettableadapters.photostableadapter"
Selectmethod= "Getphotosforalbum" >
<SelectParameters>
<asp:querystringparameter name= "albumID" querystringfield= "id" type= "Int32"/>
</SelectParameters>
</asp:ObjectDataSource>
The following example shows a ObjectDataSource bound to the Dataset.tableadapter method. In the next few examples we will use this dataset to demonstrate how to implement a simple photo album application using the ASP.net data control. Please note that the Data view in this example uses a new field type called ImageField to display the photo. We also note that the convertnulltodbnull used in ObjectDataSource causes null parameter values to be converted to DBNull (required) before being passed to the TableAdapter method.

<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" Typename= " Datacomponenttableadapters.albumstableadapter "
Selectmethod= "Getalbumsbyowner" updatemethod= "Update" convertnulltodbnull= "true" oldvaluesparameterformatstring= " Original_{0} ">
</asp:ObjectDataSource>
<asp:objectdatasource id= "ObjectDataSource2" runat= "Server" Typename= " Datacomponenttableadapters.ownerstableadapter "selectmethod=" getowners "/>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.