asp.net2.0: How to use ObjectDataSource (with ORM)

Source: Internet
Author: User
Tags implement insert log connect query sort
Asp.net|object

Asp.net2.0 inside the ObjectDataSource can make the data display control GridView, etc. to bind to display, edit. You can also support built-in paging, sorting, and more. Once you have used ORM, you can use ObjectDataSource as well.

The paging here is no longer taken out of the database, and then selectively bound, but instead the first page is fetched directly from the database and then bound. This difference is still very large, the efficiency is greatly improved.
Edit, create, sort also, provided directly by ObjectDataSource, without the need to write any code in the GridView.
In this way, the object can be designed to contain a lot of logic, at least the operation of the database, and the UI is relatively simple, peeling a little more open to later transplant to win, or made smartclient are more beneficial.

Here is a blog, speaking of relatively good http://www.evosoftworks.com/Articles/wormods.aspx.

I used exactly the same as wilsonorm, so I made one as well.

The basic structure is this:
UI (Control--objectdatasource controls such as GridView)----〉objectdatasource class (Object, write crud paging logic)---(ORM implementation crud)---〉db

There are several main steps
1: Add properties and methods to object to complete the crud, paging, and other logic
2: Configure UI controls such as GridView to connect to the ObjectDataSource control.


Let's see the first one.
1: Add properties and methods to object to complete the crud, pagination, and other logic. The object class is generated by the tool according to the DB structure, and the mapping file is also generated.
First, add a labeled attribute to the Object DataObject (), Inside the System.ComponentModel namespace [DataObject ()]
public class ProductDescription
{Second, add the Crud method to this object class.
First look at an insert method
[DataObjectMethod (Dataobjectmethodtype.insert)]
public static void Insert (ProductDescription productdescription)
{
Try
{
Manager.DataManager.StartTracking (ProductDescription, initialstate.inserted);
Manager.DataManager.PersistChanges (ProductDescription);
}
catch (Exception ex)
{
Log. Error (ex);
}
This method is preceded by a [DataObjectMethod (dataobjectmethodtype.insert)] attribute indicating that this is an Insert method;
This method is a static and open method;
argument, which is an instance of the object itself. This is better, because the logic is good to understand, is to operate on the object.
The rest of the Delete,update method is also written in this way.
Then look at the Select method, more special.
Select method
1 [DataObjectMethod (Dataobjectmethodtype.select)]
2 Public collection<productdescription> Retrieve (string query, int maxRows, int startrowindex, String sortcla Use
3 {
4 Try
5 {
6 int numpages = 0;
7 if (Sortclause = null | | sortclause = = "")
8 Sortclause = "ModifiedDate Desc";
9 Collection<productdescription> CS;
CS = retrievepage (query, Sortclause, maxRows, (int) math.ceiling (double) startrowindex/maxrows) + 1, OU T numpages);
One _numrecs = ((iobjectpage) CS). TotalCount;
Return CS;
13}
catch (Exception ex)
15 {
Log. Error (ex);
return null;
18}
19}
[DataObjectMethod (Dataobjectmethodtype.select)]
static public Objectset Retrieve (string Key, String Value)
22 {
if (Value = null | | Value = = "")
return null;
Try
26 {
Queryhelper helper = Manager.DataManager.QueryHelper;
Key = Helper. GetFieldName (typeof (ProductDescription). ToString () + "." + Key);
ObjectQuery query = new ObjectQuery (typeof (ProductDescription), String.Format ("{0}= ' {1} '", Key, Value), "");
Objectset obj = Manager.DataManager.GetObjectSet (query);
to return obj;
32}
catch (Exception ex)
34 {
Log. Error (ex);
return null;
37}
38}
39
public int RecCount (string query, int maxRows, int startrowindex, string sortclause)
41 {
return _numrecs;
43}
44
Retrievepage public static collection<productdescription> (string Whereclause, string sortclause, int PageS ize, int pageIndex, out int pagecount)
46 {
objectquery<productdescription> query = new objectquery<productdescription> (Whereclause, SortCla Use, pageSize, pageIndex);
objectset<productdescription> pageset = manager.datamanager.getobjectset<productdescription> (que RY);
PageCount = Pageset.pagecount;
return pageset;
51} The first method public collection<productdescription> Retrieve (string query, int maxRows, int startrowind Ex, string sortclause, which is a way to implement built-in paging, and sorting. Note that this code _numrecs = ((iobjectpage) CS). TotalCount; Here, after pagination, immediately take out the total number of pages, which is used for displaying page numbers; For this correspondence, method public int RecCount (string query, int maxRows, int startrowindex, String sortclause is used to remove the number of records; Note that the two methods must correspond and the parameters are the same.
The second method static public Objectset Retrieve (string Key, String Value) simply takes out a record. Can be used in the display of Detailview/formview.
The code looks a lot, but in fact it is very modular, so you can use Codesmith or directly modify the Ormhelper tool to dynamically build, do not need to write code manually.
With these four methods, CRUD, pagination, sorting is done. Such an object, which has nothing to do with the UI, is just data logic.

The configuration of the 2:ui. The UI configuration is also divided into two tiers: display controls such as GridView; ObjectDataSource controls
Now configure the object data source for controls such as GridView, connect directly to object, and implement features such as display editing. is to set a property that is connected to the ObjectDataSource.
<asp:gridview id= "Gv_data" runat= "Server" allowpaging= "true" allowsorting= "true" datasourceid= "Ods_list"

This is the configuration of the ObjectDataSource control
ObjectDataSource
1<asp:objectdatasource id= "ods_list" runat= "Server" Dataobjecttypename= "Businessmodel.productdescription"
2 deletemethod= "Delete" oldvaluesparameterformatstring= "original_{0}" selectmethod= "Retrieve"
3 typename= "Businessmodel.productdescription" updatemethod= "Update" sortparametername= "Sortclause"
4 Maximumrowsparametername= "MaxRows" selectcountmethod= "RecCount" enablepaging= "true"
5 conflictdetection= "OverwriteChanges" convertnulltodbnull= "false" >
6 <SelectParameters>
7 <asp:parameter name= "Query" type= "String"/>
8 <asp:parameter name= "MaxRows" type= "Int32"/>
9 <asp:parameter name= "startRowIndex" type= "Int32"/>
<asp:parameter name= "Sortclause" type= "String"/>
</SelectParameters>
12</asp:objectdatasource>
Look at the attributes inside, the parameters that configure the Crud method, and the corresponding method name. These are exactly what we are implementing in the class. Let's say you configure the Delete method here: deletemethod= "Delete" And here are the attributes of the number of records you just said: selectcountmethod= "RecCount", and sort, and so on.
How do we pass the parameters here? System-related attributes are passed by the system, for example, maxrows,startrowindex or something; it can also be passed in code: this.ods_list. selectparameters["Query". DefaultValue = query;



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.