Contrast .NET PETSHOP and DUWAMISH to discuss the database programming mode of ADO.NET
ADO.NET provides us with powerful database development capabilities, and its built-in multiple objects provide different options for our database. However, while allowing us to choose, many beginners are also confused, should I use DataReader or use DataAPter? I just want to read a small part of the data. Do I have to Fill full DataSet? Why can't DataReader provide a data update method like RecordSet? What is the benefit of DataSet?
In this article, I will make some simple analysis and comparison of Database programming mode of .NET PETSHOP and Duwamish database programming mode. If you have more questions, I believe that after reading this article, you can make a database programming mode that is best suited for your application according to the specific needs.
I believe that everyone must have heard the famous "pet shop war", yes, one of the protagonists in this article is the winner .Net Petshop, Microsoft's number of speeds and 1/4 code is far ahead of J2EE-based PetStore pet Shop. Although Sun also complained about this, accusing this "War" has water, but in any case, .Net PETSHOP is definitely a classic .NET instance tutorial, at least a "shortcut" that rushed to J2EE :) Its download address is: http://www.gotdotNet.com/team/compare/
And Duwamish is a simple, but an extremely complex online bookstore .NET full application example, as a Microsoft's official Sample, which provides two language versions of C # and VB.NET, and there is a lot of Detailed Chinese information, if printing, is home to travel, sleeping into the toilet must have. what? Didn't you hear it? Oh, if you have installed Visual Studio .NET, it is quietly lying quietly on your hard drive, but it is not installed, you can find and install it in your vs.net Enterprise Samples directory, for example : C: / Program Files / Microsoft Visual Studio .NET / Enterprise Samples / Duwamish 7.0 Cs.
Both stores use N-layer applications (there is no doubt that the application architecture of the N-layer structure should be absolutely the first choice for your development .NET application, even if you just want to be a web counter), the difference is that PETSHOP uses The most common three-layer application structure is a representation layer, an intermediate layer, and a data layer. DUWAMISH uses a four-layer application structure and separates from different items, which are representative layers, business appearance layers, service rules layers, and data layers. As for the advantages and disadvantages of these two structures, and why we don't make a detailed discussion, because the focus of this article is not here. We mainly analyze the model of their database programming.
First, let's take a look at the Duwamish bookstore, which uses DataAdapter and DataSet data storage mode, which is different, which makes a subcatenification extension of DataSet as a data carrier, which is to use custom DataSet to perform layers. Data transfer, 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_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 (DESCRIPTION_FIELD, typeof (System.String)); columns.Add (UNIT_PRICE_FIELD, typeof (System.Decimal)); columns.Add (UNIT_COST_FIELD, typeof (System.Decimal)); Column.add (item_type_field, typeof (syste m.String)); columns.add (publisher_name_field, typeof (system.string)); this.tables.add (table);} .........}
We can see it has a buildDataTables method, and in the constructor, this, the custom Books table is bundled with this Dataset, and saving column mapping after saving, this is a good idea, how can I not Think? :)
Solve the data structure, then look at the code implementation of the data layer, in Duwamish, 5 classes in the data layer, Books, Categories, Customers, and ORDERS, each class only responsible for access to the data. Below is a sample code for 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 code of the data layer, we can see that duwamish uses DataAdapter to populate the data into the custom DataSet and then return the Dataset. I am very strange that it can see the specific data access method of getbookbyid in the data access layer. Although there is still an abstract FillBookData method, there are three layers above, the bottom is doing this What do you do? The answer is data inspection, and the upper layer is basically doing some very strict data legitimacy checks (of course, there will be some complicated transaction logic, but not much), 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.Customers ()) {dataSet = customersDataAccess.LoadCustomerByEmail (emailAddress) } // // verify the customer's password // DATAROWCOLLECTION ROWS = dataset.tables [CustomerData.customers_table] .ROWS; IF ((rount.count == 1) && rows [0] [CustomerData.Password_field] .equals In this method, else {return null;}} is actually in this method, which is only in this way, and is the data layer that is directly called. All other are conducting legitimate checks, we can understand how important the system robustness needs to be considered for a real enterprise development.
OK, Duwamish is over, let's take a look at the data access mechanism of PETSHOP.
PETSHOP has only one project, which uses the hierarchical method to write the intermediate layer and data layer in the Components directory, where the data layer is a class named Database, which encapsulates all the underlying operations of the database. Below is a sample code segment:
public void RunProc (string procName, out SqlDataReader dataReader) {SqlCommand cmd = CreateCommand (procName, null); dataReader = cmd.ExecuteReader (System.Data.CommandBehavior.CloseConnection);}
We saw another data access method with Duwamish, which abstract all the data access methods to make a RunProc method, as for the return data, huh, it is a bit lazy, return to a DataReader to you, you Go to read yourself. Remember what the interlayer data transmission carrier used by DUWAMISH? Yes, it is DataSet, which is returned to the intermediate layer after being filled by the data layer. However, the data transmission carrier of the data layer and the transport layer becomes DataReader. In fact, it is not called a data carrier, because the data has not started reading, here, DataReader's role and pointer a bit similar, maybe we should Call it as "data reference" :) then look down, DataReader is "processed": public productResults [] getList (String catid, int currentpage, int pageSize, ref int number; {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 page int start = (int) ((currentPage - 1) * pageSize) ; If (start <= 0) st = 1;
// Skip for (INT i = 0; i
// read the data we are interested in while (Reader.Read ()) {if (index 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;}} Do you notice CurrentPage and PageSize? It turned out that the data paging was conducted here, only returned to the minimum amount of data that met, not like a lot of people who like to be lazy, simply bind the entire DataTable a brain to the DataGrid, causing a lot of data redundancy. Here, the data is real read, and is 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;}}} Very simple, but I am a little strange why not using Struct? Is the performance gap between Struct and Class in .NET already ignore it? By observing the specific implementation of these two stores, we have received two different data access modes, and duwamish uses Dataset as the core, because Dataset provides a large number of related methods this, so the data transmission, data format of the entire application Definitions, data checks are carried out around Dataset, and the entire architecture defines very clear and rigorous, but it is a bit large. PETSHOP did not use a DataSet throughout the program, the program is very simple, light, but there is no duwamish so strong. These two programs are code written by Microsoft's different teams, so they have different styles. However, you should represent the standard mode of .NET. Seeing this, you should have a comparative understanding of the questions that start with the beginning of the article. Also, note that PETSHOP is not immediately read after opening the data connection, but passes the DataReader to another object to perform the data read operation, and then turn off the connection. In this way, the data connection is longer, and the database connection is a very valuable server resource. In contrast, Dawam is filling immediately after connecting the database, and then quickly releases the database connection, which is more conducive to a large number of users. access. One point, the update operation is not mentioned above, and PETSHOP uses the COMMAND object to perform a single stored procedure to update the operation, which belongs to an online instant data update mode. Dawamish uses the DataAdapter's UPDATE method, submits the DataSet's change in a one-time submission to the database, which is an offline data update mode. The advantage of this mode is to update large quantities of data at once, reducing the number of connections to the database. The disadvantage is that if the database needs real-time tracking data change in the event of a very frequent change, it is not suitable. Specific data update methods are required to be used depending on the specific situation. In general, if you only need to quickly read the data and display it, it is recommended that you use DataReader if you need to make a lot of modifications to the data, and there is a large number of incoming access to the possibility, and does not require real-time tracking database changes. It is recommended that you use DataSet. Of course, these two sites are very extreme. The actual application environment may have a very complicated condition. Specifically, you need your own tricks, integrated, but I still prefer Petshop that kind of light style :)