Tải bản đầy đủ

Microsoft NET framework 3 5 ADO NET application development

www.it-ebooks.info


PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright © 2009 by Shawn Wildermuth, Mark Blomsma, Jim Wightman
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
without the written permission of the publisher.
Library of Congress Control Number: 2009920790
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 QWE 4 3 2 1 0 9
Distributed in Canada by H.B. Fenn and Company Ltd.
A CIP catalogue record for this book is available from the British Library.
Microsoft Press books are available through booksellers and distributors worldwide. For further infor¬mation about
international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at
fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to tkinput@microsoft.com.
Microsoft, Microsoft Press, Access, ActiveX, Bankshot Billiards, BattleTech, Blinx, Blue Dragon, Brute Force, Carbonated
Games, Crackdown, Crimson Skies, Digital Anvil, Ensemble Studios, Excel, FASA Studio, Forza Motorsport, Fuzion

Frenzy, Halo, Halo Wars, Hexic, High Road to Revenge, Infinite Undiscovery, Internet Explorer, Lost Odyssey, MechAssault,
MS, MSDN, Ninety-Nine Nights, Perfect Dark Zero, Phantom Dust, Project Gotham Racing, Quantum Redshift, Rally,
Shadowrun, Silverlight, Sneakers, SQL Server, The Time Sweeper, Visual Basic, Visual C#, Visual Studio, Viva Piñata,
Whacked!, Windows, Windows NT, Windows Server, Windows Vista, Xbox, Xbox 360 and Xbox LIVE are either
registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. Other product
and company names mentioned herein may be the trademarks of their respective owners.
The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events
depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address,
logo, person, place, or event is intended or should be inferred.
This book expresses the author’s views and opinions. The information contained in this book is provided without any
express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will
be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.
Acquisitions Editor: Ken Jones
Developmental Editor: Laura Sackerman
Project Editor: Maureen Zimmerman
Editorial Production: Christian Holdener, S4Carlisle Publishing Services
Technical Reviewer: Matt Stoecker; Technical Review services provided by Content Master, a member of CM Group, Ltd.
Cover: Tom Draper Design
Body Part No. X15-41556

www.it-ebooks.info


To Tricia:
“See it wasn’t that bad. . .”
—Shawn Wildermuth

To Marcel de Vries:
Thanks!
—Mark Blomsma

To Eleanor:
“You are #1, everyone else is #2 or lower.”
—James Wightman

www.it-ebooks.info


Contents at a Glance
Introduction



xvii

Chapter 1

Creating Database Connections

Chapter 2

Selecting and Querying Data

Chapter 3

DataSets

133

Chapter 4

Updating Data

185

Chapter 5

Synchronizing Data

237

Chapter 6

Introducing LINQ

279

Chapter 7

XML

323

Chapter 8

LINQ to SQL

361

Chapter 9

Using the Entity Framework

395

Chapter 10

ADO.NET Data Services

423

Answers

463

Glossary

479

Index

481

www.it-ebooks.info

1
83


www.it-ebooks.info


Contents


Introduction

xvii

Chapter 1 Creating Database Connections

1

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Lesson 1: Connecting to a Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Connection Object Overview

3

Lesson Summary

50

Lesson Review

50

Lesson 2: Using Data Providers and More Complex
Connection Scenarios. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Data Providers

54

Lesson Summary

68

Lesson Review

68

Lesson 3: Working with Multiple Active Result Sets. . . . . . . . . . . . . . . . . . . 71
MARS

71

Lesson Summary

79

Lesson Review

80

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Chapter Summary

81

Key Terms

81

Case Scenario

81

Suggested Practice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

What do you think of this book? We want to hear from you!
Microsoft is interested in hearing your feedback so we can continually improve our
books and learning resources for you. To participate in a brief online survey, please visit:

www.microsoft.com/learning/booksurvey/

www.it-ebooks.info

vii


Chapter 2 Selecting and Querying Data

83

Lesson 1: Building Command Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Command Object Overview

85

DbParameters Object

92

Lesson Summary

102

Lesson Review

103

Lesson 2: Consuming Data Before You Begin . . . . . . . . . . . . . . . . . . . . . . . 104
Writing Queries

104

Using DataReader

107

Using DbDataAdapter and DbTableAdapter

109

Asynchronous Queries

112

Special Datatypes

115

Using LINQ

120

Lesson Summary

129

Lesson Review

129

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Chapter Summary

131

Key Terms

131

Case Scenario

131

Suggested Practice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

Chapter 3 DataSets

133

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Lesson 1: Introduction to DataSets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
DataSet Class Hierarchy

viii

135

Reading Data from a Database

151

DataSet Datatypes

152

SQL Server User-Defined Types

153

Sample: Order and OrderDetails

153

Using a DataTableReader

160

Lesson Summary

165

Lesson Review

166

Contents

www.it-ebooks.info


Lesson 2: Working with Typed DataSets. . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Using Typed DataSets

168

Sample: Products and Suppliers

175

Lesson Summary

179

Lesson Review

180

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Chapter Summary

181

Key Terms

181

Case Scenario

182

Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Using ADO.NET in a Windows application

182

Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

Chapter 4 Updating Data

185

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Lesson 1: Updating Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Insert /Update/Delete Data Using a Command

187

Update Data Using a DataAdapter

191

Using a Command Builder

191

Performing Bulk Updates

193

Update Data Using a Table Adapter

193

Updating Custom Types

195

Using Stored Procedures

197

Sample: Updating the Database

197

Lesson Review

209

Lesson 2: Data Integrity and Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Enforcing Data Integrity in a DataSet

213

Sample: Deleting Products and Suppliers

223

Lesson Summary

233

Lesson Review

233

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Chapter Summary

235

Key Terms

235

Case Scenario

235
Contents

www.it-ebooks.info

ix


Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

Chapter 5 Synchronizing Data

237

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
Lesson 1: Caching Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Why Cache?

240

Caching Options

240

ASP.NET Caching

241

Desktop Caching

249

Lesson Summary

257

Lesson Review

257

Lesson 2: Microsoft Sync Framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
What Is the Microsoft Sync Framework?

259

Using the Sync Services for ADO.NET

261

Lesson Summary

274

Lesson Review

275

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Chapter Summary

276

Key Terms

276

Case Scenarios

276

Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Caching Data

277

Microsoft Sync Framework

277

Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

Chapter 6 Introducing LINQ

279

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Lesson 1: Constructing Queries with LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . 281

x

Why LINQ?

281

LINQ Basics

283

Your First LINQ Query

288

Expressions

292

Query Execution

296

Contents

www.it-ebooks.info


Lesson Summary

302

Lesson Review

302

Lesson 2: Shaping Results with LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Retrieving Primitive Results

304

Projecting Results into Types

305

Projecting Results into Anonymous Types

307

Joining with LINQ

308

Grouping with LINQ

311

Lesson Summary

318

Lesson Review

318

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Chapter Summary

320

Key Terms

320

Case Scenario

320

Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
Introducing LINQ

321

Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321

Chapter 7 XML

323

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Lesson 1: DataSets and XML. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Writing a DataSet as XML

325

Reading XML with a DataSet

328

DataSets and XML Schema

331

Customizing XML Serialization

336

Using DiffGrams

339

Lesson Summary

346

Lesson Review

347

Lesson 2: Querying XML with LINQ. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Introducing Queryable XML Classes

348

Constructing a Query

350

Working with Results

352

Lesson Summary

358

Lesson Review

358
Contents

www.it-ebooks.info

xi


Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Chapter Summary

359

Key Terms

359

Case Scenario

359

Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Handle special datatypes

360

Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360

Chapter 8 LINQ to SQL

361

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Lesson 1: Introduction to LINQ to SQL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
LINQ to SQL Overview

363

DataContext

364

LINQ to SQL Designer

370

Sample: Using the LINQ to SQL Designer

370

Lesson Summary

376

Lesson Review

377

Lesson 2: Updating Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
Using Dynamic SQL to Update Data

378

Updating Data in Disconnected Mode

381

Using Stored Procedures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
Sample: Adding Customers

385

Lesson Summary

390

Lesson Review

390

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Chapter Summary

392

Key Terms

392

Case Scenario

392

Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Using LINQ to SQL in a Windows Application

393

Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393

xii

Contents

www.it-ebooks.info


Chapter 9 Using the Entity Framework

395

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
Lesson 1: Generating and Querying an Entity Data Model. . . . . . . . . . . . 397
Defining the Entity Data Model

397

Using Object Services to Query Data

406

Lesson Summary

418

Lesson Review

418

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Chapter Summary

421

Key Terms

421

Case Scenario

421

Suggested Practice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422

Chapter 10 ADO.NET Data Services

423

Before You Begin. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Lesson 1: Exposing the Data Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Data Service Basics

426

Creating the Service

429

Lesson Summary

446

Lesson Review

446

Lesson 2: Consuming the Data Service. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Using an ADO.NET Data Service

447

Lesson Summary

460

Lesson Review

460

Chapter Review. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Chapter Summary

461

Case Scenarios

461

Suggested Practices. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
Using ADO.NET Data Services

462

Take a Practice Test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462

Contents

www.it-ebooks.info

xiii


xiv

Answers

463

Glossary

479

Index

481

Contents

www.it-ebooks.info


Acknowledgments

T

he authors’ names appear on the cover of this book, but the authors are only part
of a much larger team. Thank you to all of those who patiently contributed to the
­editing and production of this title including Kristy Saunders who graciously contributed
to the ­writing of the Practice Test Questions that can be found on the companion CD that
­accompanies this title.
In addition, each author would like to acknowledge the following:

Shawn Wildermuth
I would like to thank everyone involved with this book, including my co-authors, Mark and
Jim. For their help making sure that right story is told about ADO.NET Data Services, I want to
thank Pablo Castro and Mike Flasko. And finally, for answering every odd LINQ question (and
not blocking me on Instant Messenger), I want to thank Jim Wooley.

Mark Blomsma
I’d like to thank my friends and family for supporting me during the writing of this book.
Many late nights and weekends went into creating it, and sacrifices were made, plans
­cancelled last minute, and schedules rearranged. A special thank-you to my parents, who are
always there for me, and also a special word of thanks to my fellow MVPs, Marcel de Vries and
Maurice de Beijer, who never turn me away when I need help. Lastly, to my co-authors: thanks
for the experience, sharing your insights, and the fun we had creating this book!

James Wightman
Without this sounding too much like an acceptance speech at the Oscars, I would like to
thank my co-authors, Shawn and Mark, with whom it has been an honor to work, and
­everyone at Microsoft Press, including Ken Jones, Laura Sackerman, Maureen ­Zimmerman,
and Ben Ryan. For support, I cannot forget to thank Gareth Beynon, and for forgiving my
­absence from Xbox Live for most of 2008, my closest friend (and boss) Neil Cant. For the
most enjoyable and productive working environment I’ve ever had, I need to thank ­everyone
at British Telecom, including Dave Baker, Glenn Mantle, Peter Scott, Martin Neath, Lee
Ingram, Jude Mahoney, and the simply excellent Paul Prior. And finally, on behalf of every
developer out there, I want to thank William H. Gates III for giving us the opportunity to
write code for a living.

xv

www.it-ebooks.info


www.it-ebooks.info


Introduction
T

his training kit is designed for developers who plan to take Microsoft Certified Technical
Specialist (MCTS) exam 70-561, as well as for developers who need to know how to create
data-driven applications using the ADO.NET and Microsoft .NET Framework 3.5. We assume
that before you begin using this kit, you have a working knowledge of the .NET Framework,
databases, and Microsoft Visual Basic or C#.
By using this training kit, you learn how to do the following:
n

Connect to a variety of data sources

n

Query data

n

UseLanguage Integrated Query (LINQ)

n

Change data and use transactions

n

Work with the Entity Framework and LINQ to SQL for object-relational mapping

n

Synchronize data across disparate devices and tiers

n

Work with ADO.NET Data Services for Internet applications

Hardware Requirements
The following hardware is required to complete the practice exercises:
n

A computer with a 600 MHz or faster processor

n

A minimum of 192 MB of RAM

n

2 GB of available hard disk space

n

A CD-ROM drive

n

A display with a minimum of 256 colors and 1,024 x 768 resolution

n

A keyboard and a Microsoft mouse or compatible pointing device

Software Requirements
The following software is required to complete the practice exercises:
n

One of the following operating systems:

• Microsoft Windows 2000 SP4
• Windows XP SP 2
• Windows XP Professional x64 edition (WOW)
xvii

www.it-ebooks.info







n

Windows Server 2003 SP 1
Windows Server 2003, x64 edition (WOW)
Windows Server 2003 R2
Windows Server 2003 R2, x64 edition (WOW)
Windows Vista

Microsoft Visual Studio 2008 SP1
NOTE

evaLUatION eDItION OF vISUaL StUDIO

A 90-day evaluation edition of Visual Studio 2008 Professional edition is included on a
DVD with this training kit.
n

Microsoft SQL Server Express (normally installed with Visual Studio 2008) .

Using the CD
A companion CD is included with this training kit . The companion CD contains the following:
n

practice tests You can reinforce your understanding of how to create ADO .NET 3 .5
applications by using electronic practice tests that you customize to meet your needs
from the pool of “Lesson Review” questions in this book . Alternatively, you can practice
for the 70-561 certification exam by using tests created from a pool of 200 realistic
exam questions, which is enough to give you many different practice exams to ensure
that you’re prepared .

n

Code

n

an eBook An electronic version (eBook) of this book is included for times when you
don’t want to carry the printed book with you . The eBook is in Portable Document
Format (PDF), and you can view it by using Adobe Acrobat or Adobe Reader .

Most chapters in this book include sample files associated with the lab exercises
at the end of every lesson . For some exercises, you are instructed to open a project
prior to starting the exercise . For other exercises, you create a project on your own
and need to reference a completed project on the CD if you experience a problem
following the exercise .

Digital Content for Digital Book Readers: If you bought a digital-only edition of this book, you can
enjoy select content from the print edition’s companion CD.
Visit http://go.microsoft.com/fwlink/?LinkId=142363 to get your downloadable content. This content
is always up-to-date and available to all readers.

xviii

Introduction

www.it-ebooks.info


How to Install the Practice Tests
To install the practice test software from the companion CD to your hard disk, perform the
following steps:
1.

Insert the companion CD into your CD drive and accept the license agreement . A CD
menu appears .
NOTE

IF the CD MeNU DOeSN’t appear

If the CD menu or the license agreement doesn’t appear, AutoRun might be disabled on
your computer. Refer to the Readme.txt file on the CD for alternate installation instructions.

2.

Click the Practice Tests item and follow the instructions on the screen .

How to Use the Practice Tests
To start the practice test software, follow these steps:
1.

Click Start, All Programs, Microsoft Press Training Kit Exam Prep . A window appears
that shows all the Microsoft Press training kit exam prep suites installed on your
computer .

2.

Double-click the lesson review or practice test that you want to use .

NOTE

LeSSON revIeWS vS. praCtICe teStS

Select the (70-561) Microsoft .NET Framework 3.5, ADO.NET Application Development
to use the questions from the “Lesson Review” sections of this book. Select the (70-561)
Microsoft .NET Framework 3.5, ADO.NET Application Development to use a pool of 200
practice test questions similar to those on the 70-561 certification exam.

Lesson Review Options
When you start a lesson review, the Custom Mode dialog box appears so that you can
configure your test . You can click OK to accept the defaults, or you can customize the number
of questions you want, how the practice test software works, which exam objectives you want
the questions to relate to, and whether you want your lesson review to be timed . If you’re
retaking a test, you can select whether you want to see all the questions again or only those
questions you missed or didn’t answer .

After you click OK, your lesson review starts .
n

To take the test, answer the questions and use the Next, Previous, and Go To buttons
to move from question to question .

Introduction

www.it-ebooks.info

xix


n

After you answer an individual question, if you want to see which answers are
­correct—along with an explanation of each correct answer—click Explanation.

n

If you’d rather wait until the end of the test to see how you did, answer all the
­questions and then click Score Test. You see a summary of the exam objectives you
chose and the percentage of questions you got right, both overall and per objective.
You can print a copy of your test, review your answers, or retake the test.

Practice Test Options
When you start a practice test, you choose whether to take the test in Certification Mode,
Study Mode, or Custom Mode, as follows:
n

Certification Mode  Closely resembles the experience of taking a certification exam. The

test has a set number of questions, it’s timed, and you can’t pause and restart the timer.
n

Study Mode  Creates an untimed test in which you can review the correct answers
and the explanations after you answer each question.

n

Custom Mode  Gives you full control over the test options so that you can customize
them as you like.

In all modes, the user interface you see when taking the test is basically the same, but
with different options enabled or disabled, depending on the mode. The main options are
discussed in the section entitled “Lesson Review Options,” earlier in this Introduction.
When you review your answer to an individual practice test question, a “­References”
s­ ection is provided that lists the location in the training kit where you can find the
­information that relates to that question and also provides links to other sources of
­information. After you click Test Results to score your entire practice test, you can click the
Learning Plan tab to see a list of references for every objective.

How to Uninstall the Practice Tests
To uninstall the practice test software for a training kit, use the Add Or Remove Programs
­option in Control Panel in Windows (in Vista this is called Programs and Features).

Microsoft Certified Professional Program
The Microsoft certifications provide the best method of demonstrating your command of
current Microsoft products and technologies. The exams and corresponding certifications
are developed to validate your mastery of critical competencies as you design and develop,
or implement and support, solutions with Microsoft products and technologies. Computer
professionals who become Microsoft-certified are recognized as experts and are sought after

xx

Introduction

www.it-ebooks.info


industry-wide . Certification brings a variety of benefits to the individual and to employers and
organizations .
MORE INFO

aLL the MICrOSOFt CertIFICatIONS

For a full list of Microsoft certifications, go to http://www.microsoft.com/learning/mcp/
default.asp.

technical Support
Every effort has been made to ensure the accuracy of this book and the contents of the
companion CD . If you have comments, questions, or ideas regarding this book or the
companion CD, please send them to Microsoft Press by using either of the following
methods:
e-mail:
tkinput@microsoft.com
postal Mail:
Microsoft Press
Attn: MCTS Self-Paced Training Kit (Exam 70-561): Microsoft .NET Framework 3.5—ADO.NET
Application Development Editor
One Microsoft Way
Redmond, WA 98052–6399
For additional support information regarding this book and the CD-ROM ( including
answers to commonly asked questions about installation and use), visit the Microsoft
Press Technical Support Web site at http://www.microsoft.com/learning/support/books/ .
To connect directly to the Microsoft Knowledge Base and enter a query, visit
http://support.microsoft.com/search/ . For support information regarding Microsoft
software, please connect to http://support.microsoft.com .

evaluation edition Software Support
The 90-day evaluation edition provided with this training kit is not the full retail product
and is provided only for the purposes of training and evaluation . Microsoft and Microsoft
Technical Support do not support this evaluation edition .
Information about any issues relating to the use of this evaluation edition with this training
kit is posted to the Support section of the Microsoft Press Web site (http://www.microsoft.com/
learning/support/books/ ) . For information about ordering the full version of any Microsoft
software, please call Microsoft Sales at (800) 426-9400 or visit http://www.microsoft.com.
Introduction

www.it-ebooks.info

xxi


www.it-ebooks.info


C HAPTER 1

Creating Database
Connections
U

sing ADO.NET to consume a data source must begin with creating a connection. One of
the fundamental pillars of ADO.NET is the Connection object, which provides a highly
configurable conduit through which a data source may be consumed and manipulated.
The ADO.NET Connection object exposes a number of simple properties and methods,
encapsulating a complex and incredibly flexible connection framework. Connection objects
are inherited from a common set of base classes allowing specific data providers to be
used, which takes direct advantage of each data source type. Data provider properties are
configured through the Connection object instance, allowing access to security credentials,
encryption, and other properties.
This chapter provides an introduction to the available methods of connecting to a data
source. Lesson 1, “Connecting to a Data Source,” covers the basic ­connection, connecting to
a native SQL Server source. Lesson 2, “Using Data Providers and More ­Complex Connection
Scenarios,” explores database connections in more detail and also examines ­connecting to
other kinds of data sources. Lesson 3, “Working with Multiple Active Result Sets,” looks at how
to use Multiple Active Result Sets.

Exam objectives in this chapter:
n

Manage connection strings.

n

Manage connection objects.

n

Work with data providers.

n

Connect to a data source by using a generic data access interface.

n

Handle and diagnose database connection exceptions.

Lessons in this chapter:
n
n

n

Lesson 1: Connecting to a Data Source  3
Lesson 2: Using Data Providers and More Complex
Connection Scenarios  54
Lesson 3: Working with Multiple Active Result Sets  71



www.it-ebooks.info

CHAPTER 1

1


Before you Begin
To complete the lessons in this chapter, you must have:
n

A computer that meets or exceeds the minimum hardware requirements listed in the
“Introduction” section at the beginning of the book

n

Microsoft Visual Studio 2008 Professional edition installed on your computer, along
with the Microsoft .NET Framework version 3 .5

n

An understanding of Microsoft Visual Basic or C# syntax and familiarity with the .NET
Framework version 3 .5 SP1

n

A relational database, such as a recent version of Microsoft SQL Server

REAL WORLD
James Wightman

T

o fully appreciate the power and performance of ADO.NET 3.5, one must recall
its more humble beginnings—from Data Access Objects (DAOs), Remote Data

Objects (RDOs), ActiveX Data Objects (ADOs), and the earlier versions of ADO.NET
that shipped with previous editions of the .NET Framework. Since 1996, Microsoft
has been building on their Data Access technology—previously known as Microsoft
Data Access Components (MDAC)—rapidly evolving capability and performance
with each release.
Setting up the database connection has always been the first step when developing
a Microsoft Windows–based software solution. Generally speaking, the majority
of the decisions about how to connect to a data source revolve around the
target database technology and the type of security being used. From project to
project, many of the configurable options stay the same—for example, the use
of connection pooling, the type of data provider, timeout thresholds, and other
connection properties.
The reality is that while you are typically using identical code in each project to
connect to your desired data source—except for modifying the connection string
slightly, that is—it is incredibly useful to appreciate the nuances and subtleties of
the Connection object for those times where a project veers from the well-trodden
path. Many developers I know have created a set of classes—helpers, if you will—that
contain the code necessary to connect to a data source and can be reused in different
projects. I personally take the time to review my database helper classes regularly
so I can use the latest and most appropriate features of ADO.NET. Aside from these
occasional updates, I can reuse my database helper classes each time I need to
consume a data source, which means I can concentrate on implementing business
rules instead of worrying about how I’m consuming the data.

2

CHAPTER 1

Creating Database Connections

www.it-ebooks.info


Lesson 1: Connecting to a Data Source
Having a connection to a data source is fundamental to working with your data . Although
conceptually simple, the way in which a database connection is made and maintained colors
the subsequent data access experience . Any good database access technology retains this
fundamental simplicity, and ADO .NET is no different . It provides a fully featured, highly
configurable object model with which to connect to your data source . In this lesson, you learn
how to use the object model and connect to a native SQL Server database using available
security options and the most-used configuration options .

After this lesson, you will be able to:
n

Describe the ADO .NET Connection object

n

Identify the most frequently configured properties of a database connection

n

Connect to a native SQL Server data source

Estimated lesson time: 60 minutes

Connection Object Overview
The Connection object is effectively the topmost layer through which all data access
requests pass . Configuration is performed through exposed properties . The Connection
object is used with other objects in the ADO .NET object model to perform operations on a
target data source .
Figure 1-1 shows a simple overview of the four pillars of the ADO .NET object model . This
chapter concentrates on the Connection object, whereas Chapter 2, “Selecting and Querying
Data,” looks at querying data using the DataReader and DataAdapter .
Connection

DataReader

Transaction

Command

DataAdapter

Parameters

FIgUre 1-1 The ADO .NET object model

Lesson 1: Connecting to a Data Source

www.it-ebooks.info

CHAPTER 1

3


In its simplest form, a database connection can be opened using only a few lines, as
­follows:
' VB
Imports System.Data.SqlClient

Module Module1

Sub Main()

' configure and open the database connection here
Dim theConnection As New SqlConnection()

theConnection.ConnectionString = "Data Source=jim-pc;Initial
Catalog=VideoGameStoreDB;Integrated Security=SSPI;"

theConnection.Open()

If (theConnection.State = System.Data.ConnectionState.Open) Then
Console.WriteLine("Database Connection is Open")
End If

End Sub

End Module

// C#
using System;
using System.Data.SqlClient;

namespace TK70561
{
class Program
{
static void Main(string[] args)
{
// configure and open the database connection here
SqlConnection theConnection = new SqlConnection();

theConnection.ConnectionString = "Data Source=jim-pc;Initial
Catalog=VideoGameStoreDB;Integrated Security=SSPI;";

theConnection.Open();

4

CHAPTER 1

Creating Database Connections

www.it-ebooks.info


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×
x