Compare. NET PetShop and Duwamish to discuss the database programming mode of Ado. NET.

Source: Internet
Author: User
Tags format definition
Comparison. NET PetShop and Duwamish to discuss Ado. NET database programming mode overview Ado. NET provides us with powerful database development capabilities, and 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, Microsoft claims to be 27 times faster and 1/4 of the Code volume is 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 n-layer application structure (there is no doubt that the application architecture of n-layer structure 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 performs subclass extension on DataSet as a data carrier, that is, using a custom DataSet for inter-layer data transmission. 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 = ta Ble. columns; columns. add (PKID_FIELD, typeof (System. int32); columns. add (TYPE_ID_FIELD, typeof (System. int32); columns. add (PUBLISHER_ID_FIELD, 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 (DESCRIPT ION_FIELD, typeof (System. string); columns. add (UNIT_PRICE_FIELD, typeof (System. decimal); columns. add (UNIT_COST_FIELD, typeof (System. decimal); columns. 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 need 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 perf SqlParameter 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. here we can see that Duwamish uses DataAdapter to Fill the data into the custom DataSet, then return 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 is actually used for data access. loadCustomerByEmail (emailAddress); this is the data layer called directly. The others are checking validity. We can find out how important it is to consider system robustness for enterprise-level development .. NET PetShop Data Access analysis OK, Duwamish finished reading, Next let's look at the PetShop data access mechanism. 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 an example code segment: 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 the data access methods into a RunProc method. What about the returned data, well, it's a bit lazy. You can directly return a DataReader to 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 a pointer. Maybe we should call it "Data Reference" :) next, let's look at how the 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 The specified page int start = (int) (currentPage-1) * pageSize); if (start <= 0) start = 1; // skip for (int I = 0; I <start-1; I ++) {if (reader. read () numResults ++;} if (start> 1) reader. read (); // read the data we are interested in while (reader. read () {if (index <pageSize) {results [index] = new ProductResults (); results [index]. productid = reader. getString (0); results [index]. name = Reader. getString (1); index ++;} numResults ++;} reader. close (); // see if need to redim array if (index = pageSize) return results; else {// not a full page, redim array ProductResults [] results2 = new ProductResults [index]; Array. copy (results, results2, index); return results2 ;}} 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 props public string productid {get {return m_productid;} set {m_productid = value ;}} public string name {get {return m_name ;} set {m_name = value ;}} is very simple, but I am a bit surprised why not 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 does not use a DataSet in the entire program. The program is 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 have a better understanding of the questions raised at the beginning of the article. 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.