Summary : Ado. NET and
Sqldatasource This makes it easy for people to access two layers of data in ASP. NET 2.0. However, they are applied at Layer n. Program Is not so effective, and
Objectdatasource But it can provide the same ease of use for business objects in n-tier applications. Learn how to use ASP. NET 2.0 Framework and use
Objectdatasource Controls generate multi-layer Web applications in a strict sense.
Introduction
In Microsoft ASP. NET 2.0 Framework, database access is greatly simplified. Use the brand newSqldatasourceControl, you do not need to write a lineCodeYou can select, update, insert, and delete database data.
When a simple application is generated,SqldatasourceControls are a good choice. If you need to quickly generate a Web page that allows users to display and edit database records, useSqldatasourceThe widget can complete this operation within several minutes.
For example, I generated such a page on time. Combined UseSqldatasourceControls andGridviewControl. Within 1 minute 15 seconds, a page is generated to display the content of the northwind products database table. It's so fast!
However,SqldatasourceControl. If you useSqldatasourceControl, you are doing a bad thing.SqldatasourceThe disadvantage of the control is that it forces you to mix the user interface layer with the business logic layer. Any application architect will tell you that the behavior of mixing multiple layers is not advisable.
When generating multi-layer Web applications in a strict sense, you should have a clear user interface layer, business logic layer, and data access layer. Only becauseSqldatasourceIt is totally wrong to reference SQL statements or stored procedures at the user interface layer.
So why do you need to care about these things? Yes. In many cases, you don't have to worry about it. If you are creating a simple web application, you can useSqldatasourceControl. For example, if you need to generate an application composed of individual pages to display the contents of the database table, it is unwise to divide the application into multiple application layers.
Unfortunately (if you have already paid tuition fees, You will be lucky), not all web applications are simple. After an application reaches a certain level of complexity, if it is divided into multiple application layers, it is easier to generate and maintain them.
Dividing an application into multiple application layers has many advantages. If you have a clear business logic layer, you can create a keystore library that can be called from multiple pages. In other words, creating a clear business logic layer improves code reuse. In addition, creating a clear and independent application layer makes the application easier to modify. For example, a clear hierarchy allows you to modify the user interface without modifying the data access code.
If you need to use ASP. NET Framework to generate multi-layer Web applications, you can use another new control introduced by ASP. NET 2.0 Framework:ObjectdatasourceWidgetObjectdatasourceControls allow youGridviewAndDropdownlistThis user interface control is bound to an intermediate layer component.
This articleArticleIsObjectdatasourceControl. In this article, you will learn how to use this control to display and edit database data. We will also discuss how to use them in combination.ObjectdatasourceControls andSqldatasourceControls to simplify database access.
Use the objectdatasource control to edit data
ObjectdatasourceThe control contains four important attributes:SelectmethodProperties,UpdatemethodProperties,InsertmethodAttributes andDeletemethodAttribute. Using these attributes, you can specify all the methods required to perform standard database operations.
Example:
Bind to data access layer
The data access layer component encapsulates ADO. Net code to query and modify databases using SQL commands. It generally extracts detailed information about creating ADO. net connections and commands, and discloses such details through methods that can be called using appropriate parameters. The typical data access layer components can be made public as follows:
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 );
}
operations recorded in the database are usually defined at the business logic access layer, the preceding four methods are defined: getrecords, UpdateRecord, deleterecord, and insertrecord to read, update, delete, and insert data in the database, these methods are basically defined based on the select, update, delete, and insert statements in SQL.
in response to the preceding method, objectdatasource provides four attributes to set the data processing referenced by the control. You can associate the data type as follows, the Code is as follows
selectmethod = "getrecords"
updatemethod = "UpdateRecord"
deletemethod = "deleterecord"
insertmethod = "insertrecord"
/>
set selectmethon to getrecords () in mydatablllayer () method, you must note that the objectdatasource is designed to simplify the data in a declared manner The value of selectmethod is getrecords instead of getrecords ().
Similarly, the updatemethod/deletemethod/insertmethod corresponds to the UpdateRecord
/deleterecord/insertrecord method.
When getrecords () is defined above, we can see that the type returned by this method is dataview. Since objectdatasource will be used as the data source for the bound control, therefore, its return type must be one of the following:
Ienumerable, datatable, dataview, dataset, or object.
In addition, objectdatasource also has an important attribute typename. The objectdatasource control uses the reflection technology to call corresponding methods from class objects at the business logic program layer, therefore, the property value of typename is the class name used to identify the control during operation. The following example shows the basic usage of objectdatasource.
In this example, a data business logic layer is defined to process database links and business logic. These processes are processed by the northwnddb in the app_code folder. after the CS file is complete, let's take a rough look at the methods defined in the file:
Using system;
Using system. configuration;
Using system. Data;
Using system. Data. sqlclient;
Using system. Collections. Generic;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Public class employeeinfo
{
Private string _ connectionstring;
Public employeeinfo ()
{_ Connectionstring =
Configurationmanager. connectionstrings ["northwind"]. connectionstring;
}
Public sqldatareader getemployees ()
{
Sqlconnection con = new sqlconnection (_ connectionstring );
String selectstring = "select employeeid, lastname, firstname, title, address, city, region, postalcode from employees order by employeeid ";
Sqlcommand cmd = new sqlcommand (selectstring, con );
Con. open ();
Sqldatareader DTR =
Cmd. executereader (commandbehavior. closeconnection );
Return DTR;
}
Public void updateemployee (INT employeeid, string lastname, string firstname, String title, string address, string city, string region, string postalcode)
{
Sqlconnection con = new sqlconnection (_ connectionstring );
String updatestring = "Update employees set address = @ address, city = @ city where employeeid = @ employeeid ";
Sqlcommand cmd = new sqlcommand (updatestring, con );
Cmd. Parameters. addwithvalue ("@ address", address );
Cmd. Parameters. addwithvalue ("@ City", city );
Cmd. Parameters. addwithvalue ("@ employeeid", employeeid );
Con. open ();
Cmd. executenonquery ();
Con. Close ();
}
Public void deleteemployee (INT employeeid)
{
Sqlconnection con = new sqlconnection (_ connectionstring );
String deletestring = "delete employees where Employeeid = @ employeeid ";
Sqlcommand cmd = new sqlcommand (deletestring, con );
Cmd. Parameters. addwithvalue ("@ employeeid", employeeid );
Con. open ();
Cmd. executenonquery ();
Con. Close ();
}
}
In this Code, the getemployees method is defined to obtain information about all employees. The updateemployee method updates basic information about employees and the deleteemployee method deletes employee information, in this way, the following code can be used in objectcece1.aspx to call the processing of business logic:
<Asp: gridview
Id = "gridview1"
Performanceid = "objectperformance1"
Datakeynames = "employeeid"
Autogeneratecolumns = "true"
Autogenerateeditbutton = "true"
Autogeneratedeletebutton = "true"
Runat = "server" cellpadding = "4" font-names = "verdana" font-size = "X-small" forecolor = "#333333" gridlines = "NONE">
... ...
</ASP: gridview>
<Asp: objectdatasource
Id = "objectperformance1"
Typename = "employeeinfo"
Selectmethod = "getemployees"
Updatemethod = "updateemployee"
Deletemethod = "deleteemployee"
Runat = "server">
<Updateparameters>
<Asp: parameter name = "employeeid" type = "int32"/>
<Asp: parameter name = "Address"/>
<Asp: parameter name = "city"/>
</Updateparameters>
</ASP: objectdatasource>
the above uses the grieview control, which will be introduced later. Here we focus on the use of the objectdatasource control, in this control, set typename to "employeeinfo" to indicate that the class name to be called in the future is employeeinfo, the methods used to call selectmethond/updatemethod/deletemethod are the getemployees/updateemployee/deleteemployee methods in the employeeinfo class.
you can test the operation on your own. Click "edit" in the running result to update the employee information and click "delete" to delete the employee information.
in the preceding example, the updateemployee is defined as follows:
Public void updateemployee (INT employeeid, string lastname, string firstname, String title, string address, string city, string region, string postalcode)
{......
cmd. parameters. addwithvalue ("@ address", address);
cmd. parameters. addwithvalue ("@ City", city);
cmd. parameters. addwithvalue ("@ employeeid", employeeid);
......
}
This Code indicates that only the address and the city of the employee are updated when updating the employee information, and for the name (firstname, lastname) and title (title) is not updated.
Since fistname, lastname, and title are not updated, why not write updateemployee as follows?
Public void updateemployee (INT employeeid string address, string city ,)
{......
Cmd. Parameters. addwithvalue ("@ address", address );
Cmd. Parameters. addwithvalue ("@ City", city );
Cmd. Parameters. addwithvalue ("@ employeeid", employeeid );
......
}
That is to say, only three required parameters are retained and other variables are not written. If this is done, the following error occurs:
The error message is: objectperformance1 cannot find a non-generic method that contains the address, city, lastname, firstname, title, region, postalcode, and employee parameters. (I have not verified the cause, in my opinion, objectdatasource automatically generates Delete, insert, and update statements based on select statements. Therefore, this parameter is also required during update. You can view the description of selectmethod on the following msdn:
Http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.selectmethod (vs.80). aspx
).
Most of the examples I see are written as follows:
Public void updateemployee (INT employeeid, string lastname, string firstname, String title, string address, string city, string region, string postalcode)
{
Updateemployee (employeeid, address, city)
}
Public void updateemployee (INT employeeid, string address, string City)
{
Sqlconnection con = new sqlconnection (_ connectionstring );
String updatestring = "Update employees set address = @ address, city = @ city where employeeid = @ employeeid ";
Sqlcommand cmd = new sqlcommand (updatestring, con );
Cmd. Parameters. addwithvalue ("@ address", address );
Cmd. Parameters. addwithvalue ("@ City", city );
Cmd. Parameters. addwithvalue ("@ employeeid", employeeid );
Con. open ();
Cmd. executenonquery ();
Con. Close ();
}
The updateemployee method is overloaded to facilitate data expansion and maintenance.
Bind to business logic
To better process the business, we need to further encapsulate the business logic to return a strong type. For example, we define a product to encapsulate the database, which is implemented by the product. CS class and placed in the app_code directory.
Using system;
Public class product
{
Protected int _ productid;
Protected string _ productname;
Protected int _ categoryid;
Protected decimal _ price;
Protected int _ instore;
Protected string _ description;
Public int productid
{
Get {return _ productid ;}
Set {_ productid = value ;}
}
Public String productname
{
Get {return _ productname ;}
Set {_ productname = value ;}
}
Public int categoryid
{
Get {return _ categoryid ;}
Set {_ categoryid = value ;}
}
Public decimal price
{
Get {return _ price ;}
Set {_ price = value ;}
}
Public int instore
{
Get {return _ instore ;}
Set {_ instore = value ;}
}
Public String description
{
Get {return _ description ;}
Set {_ description = value ;}
}
Public Product ()
{}
Public Product (INT productid, string productname, int categoryid, decimal price, int instore, string description)
{
This. _ productid = productid;
This. _ productname = productname;
This. _ categoryid = categoryid;
This. _ price = price;
This. _ instore = instore;
This. _ description = description;
}
}
Then define the business logic class productdb. CS for processing:
Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Collections. Generic;
Using system. Data. sqlclient;
/// <Summary>
/// Summary of productdb
/// </Summary>
Public class productdb
{
Public productdb ()
{
//
// Todo: add the constructor logic here
//
}
Public list <product> getproduct ()
{
List <product> Products = new list <product> ();
Sqlconnection conn = new sqlconnection (configurationmanager. connectionstrings ["mydatabase"]. connectionstring );
String commandtext = "select * from products ";
Sqlcommand command = new sqlcommand (commandtext, Conn );
Conn. open ();
Sqldatareader DR = command. executereader ();
While (dr. Read ())
{
Product prod = new product ();
Prod. productid = (INT) Dr ["productid"];
Prod. productname = (string) Dr ["productname"];
Prod. categoryid = (INT) Dr ["categoryid"];
Prod. Price = (decimal) Dr ["price"];
Prod. instore = (int16) Dr ["instore"];
Prod. Description = (string) Dr ["Description"];
Products. Add (prod );
}
Dr. Close ();
Conn. Close ();
Return products;
}
Public void updateproduct (product Pro)
{
Sqlconnection conn = new sqlconnection (configurationmanager. connectionstrings ["mydatabase"]. connectionstring );
Sqlcommand updatecmd = new sqlcommand ("update products set productname = @ productname, categoryid = @ categoryid, price = @ price, instore = @ instore, description = @ description where productid = @ productid ", Conn );
Updatecmd. Parameters. Add (New sqlparameter ("@ productname", Pro. productname ));
Updatecmd. Parameters. Add (New sqlparameter ("categoryid", Pro. categoryid ));
Updatecmd. Parameters. Add (New sqlparameter ("@ price", Pro. Price ));
Updatecmd. Parameters. Add (New sqlparameter ("@ instore", Pro. instore ));
Updatecmd. Parameters. Add (New sqlparameter ("@ description", Pro. Description ));
Updatecmd. Parameters. Add (New sqlparameter ("@ productid", Pro. productid ));
Conn. open ();
Updatecmd. executenonquery ();
Conn. Close ();
}
Public void deleteproduct (product Pro)
{
Sqlconnection conn = new sqlconnection (configurationmanager. connectionstrings ["mydatabase"]. connectionstring );
Sqlcommand delcmd = new sqlcommand ("delete from products where productid = @ productid", Conn );
Delcmd. Parameters. Add (New sqlparameter ("@ productid", Pro. productid ));
Conn. open ();
Delcmd. executenonquery ();
Conn. Close ();
}
}
Finally, create a front-end page file and add the objectdatasource control to display data.
<Asp: objectdatasource id = "objectperformance1" runat = "server" dataobjecttypename = "product"
Deletemethod = "deleteproduct" selectmethod = "getproduct" typename = "productdb" updatemethod = "updateproduct">
</ASP: objectdatasource>
<Asp: gridview id = "gridview1" runat = "server" autogeneratedeletebutton = "true" autogenerateeditbutton = "true"
Cellpadding = "4" datakeynames = "productid" performanceid = "objectperformance1" font-names = "verdana"
Font-size = "XX-small" forecolor = "#333333" gridlines = "NONE">
<Footerstyle backcolor = "#1c5e55" font-bold = "true" forecolor = "white"/>
<Rowstyle backcolor = "# e3eaeb"/>
<Editrowstyle backcolor = "#7c6f57"/>
<Selectedrowstyle backcolor = "# c5bbaf" font-bold = "true" forecolor = "#333333"/>
<Pagerstyle backcolor = "#666666" forecolor = "white" horizontalalign = "center"/>
<Headerstyle backcolor = "#1c5e55" font-bold = "true" forecolor = "white"/>
<Alternatingrowstyle backcolor = "white"/>
</ASP: gridview>