) Compare. Net petshop and duwamish to explore the database programming mode of ADO. net.

Source: Internet
Author: User
Tags format definition
Summary ADO. NET provides us with powerful database development capabilities. Multiple built-in objects provide different options for our database programming. However, when we allow flexible selection, many beginners are also confused. Should I use datareader or dataadapter? I only want to read a small amount of data. Do I have to fill the entire dataset with fill? Why can't datareader provide a data update method like recordset? What are the advantages of dataset? In this article, I will make some simple analysis and comparison on the. NET petshop database programming mode and duwamish database programming mode. If you have any of the above questions, I believe that after reading this article, you can develop a database programming mode that best suits your application according to your specific needs. Directory
    • Brief Introduction to. Net petshop and duwamish
    • Structure Description
    • Duwamish Data Access Analysis
    • Analysis of. Net petshop Data Access
    • Analysis Summary
. Net petshop and duwamish are simple introductions. I believe you have heard of the famous "Pet Store wars". Yes, one of the protagonists of this article is the winner. net petshop, which Microsoft claims to be 27 times faster and 1/4 Code Far ahead of the J2EE-based PetStore pet store. Sun has complained about this and accused the war of moisture. However ,. net petshop is definitely a classic. net instance tutorial, at least provide us with a "shortcut" to catch up with J2EE :), it is: http://www.gotdotnet.com/team/compare

. Net petshop pet Online Store homepage while duwamish is an online bookstore with simple appearance and extremely complicated interior. net complete application example, as a Microsoft official sample, it provides both C # and VB. net two language versions, and also attached a large number of detailed Chinese information, if printed out, it is really home travel, sleep essential things. What? Have you heard of it? If you have installed Visual Studio. net, it will lie quietly on your hard disk, but it has not been installed yet, you can go to your.. NET Enterprise Samples Directory, such as: C: \ Program Files \ Microsoft Visual Studio. net \ enterprise samples \ duwamish 7.0 CS.

Duwamish online e-bookstore Homepage

Structure Description both stores adopt the n-layer application structure (there is no doubt that the n-layer application architecture should be developed by you. net Applications, even if you only want to make a Web page counter), the difference is that petshop uses the most common three-tier application structure, namely the presentation layer, middle layer and data layer. Duwamish adopts a layer-4 Application structure separated by different projects, which are the presentation layer, business appearance layer, business rule layer, and data layer. We will not discuss the advantages and disadvantages of these two structures in detail, and the reasons for such a hierarchy, because the focus of this article is not here. We mainly analyze their database programming models. Duwamish Data Access analysis first, let's take a look at the duwamish bookstore, which uses the data storage mode of dataadapter and Dataset. What's different is that, it extends the dataset subclass as a data carrier, that is, it uses a custom dataset for data transmission between layers. The following is a custom dataset example:
 public class bookdata: DataSet {public bookdata () {// create the tables in the dataset // builddatatables ();} private void builddatatables () {// create the books table // datatable table = new datatable (books_table); datacolumncollection columns = table. columns; columns. add (pkid_field, typeof (system. int32); columns. add (type_id_field, typeof (system. int32); columns. add (publisher_id_fiel D, typeof (system. int32); columns. add (publication_year_field, typeof (system. int16); columns. add (isbn_field, typeof (system. string); columns. add (image_file_spec_field, typeof (system. string); columns. add (title_field, typeof (system. string); columns. add (description_field, typeof (system. string); columns. add (unit_price_field, typeof (system. decimal); columns. add (unit_cost_field, typeof (system. decimal); col Umns. add (item_type_field, typeof (system. string); columns. add (publisher_name_field, typeof (system. string); this. tables. add (table );}.........} 
We can see that it has a builddatatables method and is called in the constructor. In this way, the customized books table is bundled with the dataset, saving the time for column mapping, this is really a good idea. Why didn't I think of it? :) After resolving the data structure, let's look at the code implementation of the data layer. In duwamish, there are five classes in the data layer: books, categories, MERS MERs, and orders, each class is only responsible for data access. The following is the sample code of one of the classes:
Private sqldataadapter dscommand; Public bookdata getbookbyid (INT bookid) {return fillbookdata ("getbookbyid", "@ bookid", bookid. tostring ();} private bookdata fillbookdata (string commandtext, string paramname, string paramvalue) {If (dscommand = NULL) {Throw new system. objectdisposedexception (GetType (). fullname);} bookdata DATA = new bookdata (); sqlcommand command = dscommand. selectcommand; command. commandtext = commandtext; command. commandtype = commandtype. storedprocedure; // use stored proc for perfsqlparameter Param = new sqlparameter (paramname, sqldbtype. nvarchar, 255); Param. value = paramvalue; command. parameters. add (PARAM); dscommand. fill (data); return data ;}
Here is the data layer code. We can see that duwamish uses the dataadapter to fill the data in the Custom dataset, and then returns the dataset. I am surprised that the specific data access method such as getbookbyid can be seen in the data access layer. Although there is still an abstract fillbookdata method, there are three layers above, what does the upper layer do if the bottom layer does this? The answer is Data check. The upper layer basically performs some strict Data Validity verification (of course, it also includes some complicated transaction logic, but not many). The sample code is as follows:
Public customerdata getcustomerbyemail (string emailaddress, string password) {// check preconditions // applicationassert. checkcondition (emailaddress! = String. Empty, "email address is required", applicationassert. linenumber); applicationassert. checkcondition (password! = String. empty, "password is required", applicationassert. linenumber); // get the customer dataset // customerdata dataset; using (dataaccess. customers customersdataaccess = new dataaccess. MERs () {dataset = customersdataaccess. loadcustomerbyemail (emailaddress);} // verify the customer's password // datarowcollection rows = dataset. tables [customerdata. customers_table]. rows; If (rows. count = 1) & rows [0] [mermerdata. password_field]. equals (password) {return dataset;} else {return NULL ;}}
In this method, only
Dataset = customersdataaccess. loadcustomerbyemail (emailaddress );
In this case, the data layer is called directly. Others are verifying legitimacy. We can realize how important the robustness of the system is to be considered for a real enterprise-level development. . Net petshop Data Access analysis OK, duwamish finished reading. Let's take a look at the data access mechanism of petshop. Petshop has only one project. The hierarchical method is to write the intermediate layer and data layer as CS files in the components directory, where the data layer is a class named database, it encapsulates all underlying operations on the database. The following is a sample code snippet:
Public void runproc (string procname, out sqldatareader datareader) {sqlcommand cmd = createcommand (procname, null); datareader = cmd. executereader (system. Data. commandbehavior. closeconnection );}
We see another data access method that is completely different from duwamish. It abstracts all data access methods into a runproc method. As for the returned data, it is a bit lazy and returns a datareader to you. Read it by yourself. Do you still remember what is the cross-layer data transmission carrier used by duwamish? By the way, it is dataset, which is filled by the data layer and returned to the middle layer. But here, the data transmission carrier at the data layer and the transmission layer is changed to datareader. In fact, it cannot be called a data carrier because the data has not started to be read. Here, the role of datareader is similar to that of pointer. Maybe we should call it "Data Reference". :) next, let's look at how datareader is "processed:
 Public productresults [] getlist (string catid, int currentpage, int pagesize, ref int numresults) {numresults = 0; int Index = 0; sqldatareader reader = getlist (catid); productresults [] Results = new productresults [pagesize]; // now loop through the list and pull out items of the specified pageint start = (INT) (currentpage-1) * pagesize); If (start <= 0) Start = 1; // skipfor (INT I = 0; I 
    1) reader. read (); // read the data we are interested inwhile (reader. read () {If (index 
Have you noticed currentpage and pagesize? Previously, we performed data paging here, and only returned the minimum amount of data to meet the needs, rather than just like many of us who like to be lazy, simply bind the entire able to the DataGrid, resulting in a large amount of data redundancy. Here, the data is actually read and manually filled into a custom object array. Let's take a look at the definition of this array:
Public class productresults {private string m_productid; private string m_name; // product propspublic string productid {get {return m_productid;} set {m_productid = value ;}} public string name {get {return m_name;} set {m_name = value ;}}}
It's very simple, but I'm a little surprised why I don't use struct? Is the performance gap between struct and class in. Net NEGLIGIBLE? By observing the specific implementation of these two stores, we have obtained two different data access modes. duwamish uses dataset as the core because dataset provides a large number of related methods, therefore, the data transmission, data format definition, and data verification of the entire application are carried out around dataset. The definition of the entire architecture is very clear and rigorous, but it seems a little huge. Petshop throughout Program Without a dataset, the program is very simple and lightweight, but not as robust as duwamish. These two programs are written by different Microsoft teams, so they have different styles. However, they all represent the. NET standard mode. Here, you should Article Those questions raised at the beginning have a clear understanding. In addition, please note that after opening the data connection, petshop does not read the data immediately. Instead, it passes the datareader to another object for data read and closes the connection. In this way, the data connection time is extended, and the database connection is a very valuable server resource. In contrast, dawamish fills in immediately after connecting to the database, then, the rapid release of database connections is more conducive to concurrent access by a large number of users. Another point is that the update operation is not mentioned in the above program. petshop uses the command object to execute a single Stored Procedure for the update operation. It is an online real-time data update mode. Dawamish adopts the dataadapter update method to submit dataset changes to the database at one time, which is an offline data update mode. The advantage of this mode is that you can update a large volume of data at a time to reduce the number of database connections. The disadvantage is that it is not appropriate to track data changes in real time when the database changes frequently. Specific data update methods should be adopted according to specific situations. In general, if you only need to quickly read and display the data, we recommend that you use datareader. If you need to make a lot of changes to the data, there is a possibility of a large number of concurrent accesses, in addition, you do not need to track database changes in real time. We recommend that you use dataset. Of course, these two situations are a bit extreme, and the actual application environment may have complicated conditions. You need to review the situation on your own and use them comprehensively, however, I personally prefer petshop's lightweight style :)

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.