Data Access Mode 2: Data Sets and Data Adapters (Traditional Data Access Mode)

xiaoxiao2021-04-04  262

Previous article introduces the process of accessing the database using the DataSource control, this section describes the access database using the data adapter set / data adapter. The difference in the two design patterns, so that the GridView's design is to support the data binding mode of the DataSource control, but also support the data binding mode of the data set and data adapter. Because this is the existence of peaks, the GirdView control The design is more complicated. Of course, every day, you just need to know that these two differences and have some concepts, nor do you have to study, after all, everyone is not a control development expert. 2.4 Data set and data adapter

The VS.NET 2005 supports traditional data binding methods and provides visual operations for this manner, which will introduce data sets and data adapters.

2.4.1 Strong Type Data Set Introduction

For most applications, data access is an important link regardless of the WINDOWS FORM for future application to Web Server. Data Access is more inclined to handle read and write to the database, you can create these commonality separately, but you still need to write a lot of code.

In fact, we may have a feeling: Creating a data access layer is very boring, because the ADO.NET code for executing SQL statements or stored procedures is usually the same or similar for different methods of DAL. Although you can use the method before you can customize your own DAL, the Visual Studio provides a convenient way to generate a data access layer according to the input input of the Simple Wizard. The data access layer in this case is a strong type of DataSet object. The DataSet contains TableAdapter type, which is disclosed to return a high-type DataTable object. These methods are suitable for direct binding to ObjectDataSource, and is also suitable for calling from business logic layer components.

1) Type data set

The VS.Net 2005 provides a data set and data adapter that uses them to reduce the code writing, and the Visual Stduio.NET designer can be used to declare a strong type of data set. The data set here is also classified from ADO.NET DATASET, DATATABLE and DATAROW, which provides a secure API interface to the outside world. With the API interface, we can easily access the data and data modes in the DataSet.

You can create data access modes by using the properties designer by generating these strong type datasets in VSNET 2005. In fact, your operations generate a type of XML schema definition (XSD). The XSD file contains the database design mode structure, and the system can contain data in the DataSet according to this structure. In other words, the VS.NET 2005 will use the XSD file to generate a code file containing the data set definition.

When you access data in your application, data will be organized as a business logic entity, such as a Category entity, a Product entity, etc. according to different data tables, such as Category entities, Product entities, etc. In order to be able to use this data, you need these logic. Entity is converted to a class object, so you can write a class object for each entity. These entity objects generally provide some properties and methods for data access, you can use these properties and methods in the class to return strong type collection

Strong-type datasets provide convenience for establishing and entrusting custom class objects, from essentially you created class objects are a type of Dataset, which contains business logic entities and some data sets, but the main difference is You can write a schema file in a statement, you can use the VS.NET2005 support to edit, delete the XML data mode file, and the VS.NET can sense the changes in the mode file and update the code file class. In addition, since strong type DataSet is derived from ADO.NET, you can reuse data operations provided by ADO.NET, such as data binding, data paging, sorting, filtering, and other common work.

The last point is also the most important point. When you set the data set in the vs.net2005, you can get a strong type of data adapter table for each table, using the data adapter, you can greatly reduce the regular code. The data adapter further encapsulates the link connection of the data, the execution of Command, which will be described in detail later.

2) Comparison of DataSets and Business Objects

A common discussion is: Whether you use DataSets in your app. Although DataSet is a convenient application of application code, it has a certain limitation because of its packaging of many implementation details because of understanding and controllability. Customizing Business Objects in this regard has a bit of strong degree, it is a bit simple to understand. However, as foregoing, DataSets can reduce the repetition of classification code. In fact, for the Web, the data of the data is intended to have an important proportion than the writing of the data, so DataSet is more advantageous than Business Objects in this simple data read.

2.4.2 Establish a data set and data adapter

This book is described in Chapter 1 that explained how to build a database with VS.NET2005, which continues to use the Database database to explain the use of data sets and data adapters. In the Server Explorer view, you can see two tables in the Database database already have Categories and Products, as shown in Figure 2-42.

Figure 2-42 Database database

1) Use the DataSet designer

Next, we will establish a Database's business logic layer. In "Solution Explorer", click the Mouse and select "Add New Item ...", select "DataSet" and name Database.xsd as shown in Figure 2-43 . The DataSet established in vs.net will use the default file naming method. For example, the file established at this place is Database.xsd, and the DataSet derived class established after the system is named DATABASE. Conversely, if the DataSet created here is named MYDAL, the DataSet derived class created later is named mydal class.

Next, a dialog will pop up, ask if you add this file to the app_code directory, we select "YES" to share it later.

Note: App_code files are removed from class files * .cs, *. Xsd, web service, etc. can also share

Thereafter, the system will establish a Database.xsd file in the app_code directory and launch the Tableadapter Configuration Wizard, such as Figure 2-44 Figure 2-44 Tableadapter Configuration Wizard wizard

2) Establish the first data adapter

In Figure 2-44, click Next, you will ask if you use DatabaseConnectionstring as a connection string and save it in web.config, select the "YES" checkbox, such as introducing the next step, select the command type of the SQL statement, you can Is a SQL statement or a new stored procedure or a stored procedure already existing. Here we use the first "Use SQL Statements", as shown in Figure 2-26. Figure 2-46 Using SQL Statements In the next step, we use "Query Builder" to create a SQL statement, as shown in Figure 2-47, you can click "Execute Query" to view the results of the SQL statement.

Figure 2-47 Query Builder Inquiry

When the return will be generated, the following SQL statement will be generated, referring to Figures 2-48.

Select ProductId, ProductName, CategoryId, Price, Instore, Description

From product

Figure 2-48 Generate SQL statement

There is also an "Advanced Options ..." in Figure 2-48 (Advanced Options ... "(Advanced option), and then pop up the Advanced Options dialog box, as shown in Figure 2-49

Figure 2-49 Advanced dialog

In the advanced option, the default is "Generate Insert, Update and Delete Statements", so the system automatically generates the corresponding insert, update, and delete statements according to the SELECT statement, and "User Optimistic Concurrency" and Refresh THE DATA TABLE (refresh form data) is not selected.

Click Next, you will enter the "Choose Methods to Generate" page, which will let us name the method name in the business logic processing, here there are two types of method patterns:

Fill Class: DataSet The Fill class generates a method of DataSet or DataTable as a parameter, which will populate the data set using the SQL statement generated in front.

Get class: This type of method is used to get the previous SQL statement or the return result value executed by the stored procedure.

Figure 2-50 shows my setting, where the Fill class is a Fill method, and the method named by the Get class is getProducts.

In addition, I also selected the following GeneratedBDirectMethods so that the system will automatically generate the corresponding method according to the INSERT, UPDATE, and DELETE statements in front.

Click "Next" to display the result of the system automatically generated, if it is successful, you can complete the wizard between Finish.

When the wizard is closed, the system will automatically open the designer of the VS.NET, and you can see the class view in this designer as shown in Figure 2-51. Figure 2-51 Town to the result map

Right click on Figure 2-51, select "View Code", we can view the XSD source code generated by the system, let's see which code is generated by the system.

1, use the Connection ID database connection

The connection configuration of the database in the front width is expressed by Connections's Connection, which maps in the XSD document, such as code 2-21. As you can see, the database link also includes attributes such as Name, Provider, which are used for connections in later databases.

AppsettingSObjectName = "Web.config"

AppSettingSpropertyName = "DatabaseConnectionstring" ConnectionstringObject = ""

Isappsettingsproperty = "true"

Modifier = "assembly"

Name = "DatabaseConnectionString (Web.config"

Parameterprefix = "@"

PropertyReference = "Appconfig.System.configuration.configurationManager.0.connectionstrings.Databasetring"

Provider = "system.data.sqlclient">

Code 2-21 Database.xsd Code Fragment (1)

2, the execution of the data is expressed in xxxcommand (here is an even explanation, you can skip)

In the previous SQL statement wizard, since the system automatically generates the delete, Update, and INSERT statements and methods according to the SELECT statement, the system will use , , , and , and Establish parameters needed for these methods, such as 2-22.

ConnectionRef = "DatabaseConnectionString (Web.config)"

DBObjectName = "dbo.products" dbobjectType = "table"

FillmethodModifier = "public"

FillmethodName = "fill" generateMethods = "Both"

GeneratesheshortCommands = "true" generatorgetMethodName = "getAllProducts"

GENERATORSOURENAME = "Fill" getMethodModifier = "public"

GetMethodName = "getAllProducts" querytype = "rowset"

Scalarcallretval = "System.Object, Mscorlib, Version = 2.0.0.0, Culture = Neutral, PublickeyToken = B77A5C561934E089"

UseOptimisticConcurrency = "false"

UsergetMethodName = "getAllProducts" UserSourceName = "Fill">

delete from [product] where (([ProductID] = @original_productid))

INSERT INTO [Products] ([ProductName], [CategoryID], [Price], [InStore], [Description]) VALUES (@ProductName, @CategoryID, @Price, @InStore, @Description)

Select ProductId, ProductName, CategoryId, Price, Instore, Description

From product

UPDATE [Products] SET [ProductName] = @ProductName, [CategoryID] = @CategoryID, [Price] = @Price, [InStore] = @InStore, [Description] = @Description WHERE (([ProductID] = @ Original_productid))

Code 2-22 Database.xsd part of the code (2)

3) Use mapping mapping properties

For the column of the database, the system uses the mapping element to map to the class's properties, and sets its type, such as code 2-23.

Map of code 2-23 column and class properties

Through the above processing, we can define data adapters, data sheets, and data lines with the following methods in the code.

Databaseetableadapters.ProductStableAdapter PTA =

New DatabaseetableAdapters.ProductStableAdapter ();

Database.ProductSDataTable Table = New Database.ProductSDataTable ();

Database.productsRow Row = new database.productsrow ()

Note the default naming method when using: DatabaseTableAdapters maps the naming of the entire adapter and contains multiple data adapter tables in this namespace.

SIMPE_DATAADAPTER.ASPX demonstrates the use of the above code. Code 2-24 is Simple_DataAdapter.aspx layout code

<% @ Page language = "c #" autoeventwireup = "true" codefile = "simple_dataadapter.aspx.cs" inherits = "Simple_DataAdapter"%>%>

Font-size = "xx-small" forcolor = "# 333333" Gridlines = "none">

...

Code 2-24 Simple_DataAdapter.aspx layout code

Code 2-25 is the background code of the page.

Public Partial Class Simple_DataAdapter: System.Web.ui.page

{

Protected void Page_load (Object Sender, Eventargs E)

{

Databaseetableadapters.ProductStableAdapter PTA = New DatabaseetableAdapters.ProductStableAdapter ();

Gridview1.datasource = pta.getallproducts ();

GridView1.databind ();

}

}

Code 2-25 Simple_DataAdapter.aspx.cs Background Code

The GetAllProducts source in the code is predefined in Figure 2-52. Figure 2-52 shows the operation results. From the entire operation, we have little written code, nor can you design the details of the data database data without designing the details of ADO.NET.

Figure 2-52 Simple_DataAdapter.aspx operation results

This only demonstrates the basic use of the data set and data adapter. In fact, with the data set and data adapter can complete the work such as parameter delivery, stored procedures, etc., if you define the relationship of the table when designing the database, DataAdapter can also automatically Establish a mapping relationship. View. Still, it is used for DataAdapter display data, and implements work such as Update, Delete, etc., is indeed working hard.

If you want to know the implementation principle of DataAdapter, you can also see an article I published before.

Http://mqingqing123.cnblogs.com/archive/2005/10/11/252410.html

Because the system is done for you, it is automated compilation

The above content is for reference only, does not guarantee correctness

转载请注明原文地址:https://www.9cbs.com/read-131756.html

New Post(0)