1. Trang chủ
  2. » Công Nghệ Thông Tin

Netframwork 2.0 (phần 8) pot

50 337 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 516,68 KB

Nội dung

Lesson 5: Performing Transactions by Using the Transaction Object 325 1. How do you create a new transaction? A. Assign a transaction variable the return value of the Connection.Begin- Transaction method. B. Declare a new instance of the Transaction class. C. Call the Command.CreateTransaction method. D. Declare a new Command.Transaction object. 2. What is the main purpose of a transaction? A. To validate that multiple commands complete successfully B. To handle exceptions that may occur on the database during command execution C. To abort the outcome of an executed command and return data to the state it was in prior to the transaction D. To provide an option to abort the outcome of executed commands and return data to the state it was in prior to the transaction 3. What is the difference between a local transaction and a distributed transaction? A. Local transactions are performed on a single database table, whereas dis- tributed transactions are performed on multiple database tables. B. Local transactions are performed on a single database, whereas distributed transactions are performed on multiple databases on the same server. C. Local transactions are performed on a single database server, whereas dis- tributed transactions can be performed across multiple database servers. D. Local transactions are performed on a database on the local machine, whereas distributed transactions are performed on a database on a remote machine. 326 Chapter 6 Review Chapter Review To further practice and reinforce the skills you learned in this chapter, you can per- form the following tasks: ■ Review the chapter summary. ■ Complete the case scenarios. These scenarios set up real-world situations involv- ing the topics of this chapter and ask you to create a solution. ■ Complete the additional practices. ■ Take a practice test. Chapter Summary ■ SQL statements and stored procedures can be run using provider-specific Command objects. ■ Data returned by Command objects can be accessed through provider-specific DataReader objects. ■ Command objects have parameter collections that can contain one or more parameters for executing parameterized queries and stored procedures. ■ BLOB data can be saved and retrieved from a database using DataReaders and Stream objects. ■ Bulk copy operations can be performed using the SqlBulkCopy object as well as by executing a SQL BULK INSERT statement. ■ Commands can be executed within the context of a local transaction, or a com- mand can be enlisted in a distributed transaction. Key Terms ■ BLOB ■ parameter ■ transaction 327 Chapter 6 Review Case Scenarios In the following case scenarios, you will apply what you’ve learned about working with data in a connected environment. You can find answers to these questions in the “Answers” section at the end of this book. Case Scenario 1: Troubleshooting a Non-Performing Application You’ve been contracted by The Phone Company to investigate why their Customer Relationship Management (CRM) application is running slow, causing support techs to spend an unreasonable amount of time waiting for queries to execute. After several days of analyzing their code base and backend database, you come to the conclusion that the lack of performance is due to the exponential increase of their customer base, which is causing too many records to be fetched when running queries that were not designed with scalability in mind. You also notice the archiving utility is constantly running, moving individual records from current to history. List the potential improvements you can make to the application. Case Scenario 2: Preventing the Inventory System from Selling Unavailable Products Your biggest customer, Wide World Importers, is now selling items from many new manufacturers around the globe. Their system is set up to forward orders to the cor- rect manufacturers if local warehouses are out of stock so items can be drop-shipped to the proper customers. The main problem this poses is that they seem to be forward- ing orders for items that are not in stock or have longer than acceptable lead times, and it’s causing customers to become extremely upset. Given that each manufacturer exposes its inventory information and projected man- ufacture date for new inventory, what modifications can you make to the Wide World Importers sales application to remedy this problem? 328 Chapter 6 Review Suggested Practices To gain further knowledge on the subject of working with data in a connected envi- ronment, complete the following practices: ■ Practice 1 Create an application that saves data to the Northwind Employees table and allows you to select a picture from your hard drive to save in the Photo column. ■ Practice 2 Create an application that queries the Northwind Customers table and has separate commands to return data based on CompanyName, City, or PostalCode. ■ Practice 3 Create an application that bulk copies all Northwind Orders, which have already shipped, into a ShippedOrders table. Take a Practice Test The practice tests on this book’s companion CD offer many options. For example, you can test yourself on just the content covered in this chapter, or you can test yourself on all the 70-526 certification exam content. You can set up the test so that it closely sim- ulates the experience of taking a certification exam, or you can set it up in study mode so that you can look at the correct answers and explanations after you answer each question. MORE INFO Practice tests For details about all the practice test options available, see the “How to Use the Practice Tests” sec- tion in this book’s Introduction. Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment This chapter describes how to work with data loaded from a database or XML docu- ment into your application. ADO.NET provides several objects, such as DataSet and DataTable objects, for caching data in applications so that you can disconnect from the database and work with the data in your application and then reconnect when you are ready to save your updates back to the data source. Exam objectives in this chapter: ■ Create, add, delete, and edit data in a disconnected environment. ❑ Create a DataSet graphically. ❑ Create a DataSet programmatically. ❑ Add a DataTable to a DataSet. ❑ Add a relationship between tables within a DataSet. ❑ Navigate a relationship between tables. ❑ Merge DataSet contents. ❑ Copy DataSet contents. ❑ Create a typed DataSet. ❑ Create DataTables. ❑ Manage data within a DataTable. ❑ Create and use DataViews. ❑ Represent data in a DataSet by using XML. ❑ Use the OleDbDataAdapter object to access an ADO Recordset or Record. ❑ Generate DataAdapter commands automatically by using the Command- Builder object. 329 330 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment ❑ Generate DataAdapter commands programmatically. ❑ Populate a DataSet by using a DataAdapter. ❑ Update a database by using a DataAdapter. ❑ Resolve conflicts between a DataSet and a database by using a DataAdapter. ❑ Respond to changes made to data at the data source by using DataAdapter events. ❑ Perform batch operations by using DataAdapters. Lessons in this chapter: ■ Lesson 1: Creating DataSet Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 ■ Lesson 2: Creating DataTable Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 ■ Lesson 3: Creating DataAdapter Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 ■ Lesson 4: Working with Data in DataTable Objects . . . . . . . . . . . . . . . . . . . . . 373 ■ Lesson 5: Working with XML in DataSet Objects. . . . . . . . . . . . . . . . . . . . . . . 387 ■ Lesson 6: Creating and Using DataView Objects . . . . . . . . . . . . . . . . . . . . . . . 396 Before You Begin To complete the lessons in this chapter, you must have: ■ A computer that meets or exceeds the minimum hardware requirements listed in the “Introduction” at the beginning of the book. ■ Microsoft Visual Studio 2005 Professional Edition installed on your computer. ■ An understanding of Microsoft Visual Basic or C# syntax and familiarity with the Microsoft .NET Framework. ■ Available data sources, including Microsoft SQL Server (SQL Server Express Edi- tion is acceptable), the Northwind sample database for SQL Server, and the Nwind.mdb Microsoft Office Access database file. ■ A basic understanding of relational databases. ■ Completed the exercises or understood the concepts presented in Chapter 5, “Configuring Connections and Connecting to Data,” and Chapter 6, “Working with Data in a Connected Environment.” Before You Begin 331 Real World Steve Stein I always spent way too much time whenever I needed to create objects to cache data in my applications. With DataSet objects, the standard database structures are already there, so quickly creating a representative object model for my data is really easy. 332 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment Lesson 1: Creating DataSet Objects DataSet objects are available in the System.Data namespace and are used as an in- memory cache of the data being used in your application. DataSet objects contain DataTable objects that can be related with DataRelation objects much like the struc- ture of a relational database. After this lesson, you will be able to: ■ Create a DataSet graphically. ■ Create a typed DataSet. ■ Create a DataSet programmatically. ■ Add a DataTable to a DataSet. ■ Add a relationship between tables within a DataSet. ■ Navigate a relationship between tables. Estimated lesson time: 45 minutes DataSet Objects Datasets are objects that you use to temporarily store the data that is used in your application. There are basically two distinct kinds of DataSet objects: typed, and untyped. Untyped DataSets are the standard generic instances of the DataSet class where you manually build up the DataSet definition (schema) by creating DataTable objects (untyped DataTables) and adding them to the Tables collection in the DataSet. You can access untyped DataTable and DataColumn objects through their collection indices. Typed DataSet objects derive their schema from an .xsd file and contain explicitly typed collections (such as a specific CustomersTable object). There are three distinct ways to create DataSet objects in Visual Studio: ■ Declare a new DataSet object programmatically in the code editor, which results in an empty DataSet that requires creating DataTable and optional DataRelation objects to be added to the DataSet. ■ Use design-time tools such as the DataSet Designer and the Data Source Con- figuration Wizard which assists in the creation of typed DataSet objects by step- ping you through the process of selecting or creating a data connection and then allowing you to select database objects available from that connection to build up a typed DataSet and have most, if not all, of the necessary code gener- ated for you. Lesson 1: Creating DataSet Objects 333 ■ Drag a DataSet object from the Toolbox onto a form and use the Table and Col- umn Collection editors to build up the schema of your DataSet. This lesson describes how to create DataSet objects using each of these methods. NOTE Generating DataSet objects You can also create DataSet objects based on configured DataAdapter objects. This will be covered in Lesson 3, “Creating DataAdapter Objects,” of this chapter. Creating DataSet Objects Programmatically Create DataSet objects by declaring instances of them. You can optionally provide the name of the DataSet. For example, the following code example creates a new DataSet named NorthwindDataSet: ' VB Dim NorthwindDataset As New DataSet ("NorthwindDataset") // C# DataSet NorthwindDataset = new DataSet ("NorthwindDataset"); Adding DataTable Objects to a DataSet After declaring a new DataSet, you need to add DataTable objects to it to actually hold the data in your application. The following code sample shows how to add a Customers- Table and OrdersDataTable to the NorthwindDataset: ' VB ' Create some DataTables Dim CustomersTable As New DataTable Dim OrdersDataTable As New DataTable ' Add DataTables to the Dataset's Tables collection. NorthwindDataset.Tables.Add(CustomersTable) NorthwindDataset.Tables.Add(OrdersDataTable) // C# // Create some DataTables DataTable CustomersTable = new DataTable (); DataTable OrdersDataTable = new DataTable (); // Add DataTables to the Dataset's Tables collection. NorthwindDataset.Tables.Add(CustomersTable); NorthwindDataset.Tables.Add(OrdersDataTable); 334 Chapter 7 Create, Add, Delete, and Edit Data in a Disconnected Environment Adding a Relationship Between Tables in a DataSet After adding tables to a DataSet, you can use DataRelation objects to represent the rela- tion between DataTable objects just like the relationships between tables in a data- base. Create relationships in DataSet objects by declaring DataRelation objects and providing the columns from the parent and child tables to the DataRelation construc- tor. After creating the relationship, you must add it to the Relations collection of the DataSet. The following code sample creates a relationship in the NorthwindDataSet and assumes the Customers and Orders DataTable objects each have a CustomerID column that is used to relate the table’s data together: ' VB ' Create the new relationship. Dim CustomersOrders As New DataRelation ("CustomersOrders", _ CustomersTable.Columns("CustomerID"), OrdersTable.Columns("CustomerID")) ' Add the relationship to the DataSet. NorthwindDataset.Relations.Add(CustomersOrders) // C# // Create the new relationship. DataRelation CustomersOrders = new DataRelation ("CustomersOrders", CustomersTable.Columns["CustomerID"], OrdersTable.Columns["CustomerID"]); // Add the relationship to the DataSet. NorthwindDataset.Relations.Add(CustomersOrders); Navigate a Relationship Between Tables To access related records in DataTable objects, you must first select a DataRow from either the parent or child table and then call either the GetParentRow or GetChildRows method of the DataRow. Calling the GetParentRow method returns a single DataRow representing the parent record, whereas calling the GetChildRows method returns an array of DataRows representing all rows that are related to the selected parent. Returning the Parent Row of a Selected Child Record The following example returns the Customer of a selected Order: ' VB Dim Customer As DataRow = SelectedOrdersRow.GetParentRow("FK_Orders_Customers") // C# DataRow Customer = SelectedOrdersRow.GetParentRow("FK_Orders_Customers"); [...]... DataSet1.Tables("Products").Rows.Add(newRow7) Dim newRow8 As DataRow = DataSet1.Tables("Products").NewRow() newRow8.Item("CategoryID") = 2 newRow8.Item("ProductName") = "Chef Anton's Gumbo Mix" DataSet1.Tables("Products").Rows.Add(newRow8) Dim newRow9 As DataRow = DataSet1.Tables("Products").NewRow() newRow9.Item("CategoryID") = 3 newRow9.Item("ProductName") = "Boston Crab Meat" DataSet1.Tables("Products").Rows.Add(newRow9) // C# DataRow... dataSet1.Tables["Products"].Rows.Add(newRow7); DataRow newRow8 = dataSet1.Tables["Products"].NewRow(); newRow8["CategoryID"] = 2; newRow8["ProductName"] = "Chef Anton's Gumbo Mix"; dataSet1.Tables["Products"].Rows.Add(newRow8); DataRow newRow9 = dataSet1.Tables["Products"].NewRow(); newRow9["CategoryID"] = 3; newRow9["ProductName"] = "Boston Crab Meat"; dataSet1.Tables["Products"].Rows.Add(newRow9); 31 Create an event handler . System.Int 32 ❑ Name = ProductID 20 . Add a column and set the following properties: ❑ AllowDBNull = False ❑ ColumnName = ProductName ❑ DataType = System.String ❑ Name = ProductName 21 . Add. CategoryID ❑ DataType = System.Int 32 ❑ Name = CatID 22 . Click Close. Select the Constraints property for the Products table and add a Unique constraint. 23 . Select the ProductID column and. newRow2 As DataRow = DataSet1.Tables("Categories").NewRow() newRow2.Item("CategoryName") = "Condiments" DataSet1.Tables("Categories").Rows.Add(newRow2)

Ngày đăng: 07/07/2014, 05:20

TỪ KHÓA LIÊN QUAN