Pro LINQ
Language Integrated Query in C#
2010
Adam Freeman and Joseph C. Rattz, Jr.
Apress
Contents
Contents at a Glance IV
Contents vi
About the Author xx
About the Technical Reviewer xxi
Acknowledgments xxii
Part 1: Pro LINQ: Language Integrated Query in C# 2010 1
Chapter 1: Hello LINQ 3
A Paradigm Shift 3
Query XML 4
Query a SQL Server Database 5
Introduction 7
LINQ Is About Data Queries 7
How to Obtain LINQ 8
LINQ Is Not Just for Queries 8
Tips to Get You Started 12
Use the var Keyword When Confused 12
Use the Cast or OfType Operators for Legacy Collections 14
The OfType Operator versus the Cast Operator 15
Don't Assume a Query Is Bug-Free 15
Take Advantage of Deferred Queries 16
Use the DataContext Log 17
Use the LINQ Forum 18
Summary 18
vi
CONTENTS
Chapter 2: C# Language Enhancements for LINQ 21
C# Language Additions 21
Lambda Expressions 22
Expression Trees 27
Keyword var, Object Initialization, and Anonymous Types 28
Extension Methods 33
Partial Methods 39
Query Expressions 41
Summary 52
Part 2: LINQ to Objects 55
Chapter 3: LINQ to Objects Introduction 57
LINQ to Objects Overview 57
IEnumerable<T>, Sequences, and the Standard Query Operators 58
Returning IEnumerable<T>, Yielding, and Deferred Queries 59
Func Delegates 62
The Standard Query Operators Alphabetical Cross-Reference 64
A Tale of Two Syntaxes 66
Summary 66
Chapter 4: Deferred Operators 69
Referenced Namespaces 69
Referenced Assemblies 69
Common Classes 69
The Deferred Operators by Purpose 71
Restriction 71
Projection 74
Partitioning 85
Concatenation 93
Ordering 96
Join 116
vii
CONTENTS
Grouping
Set 126
Conversion 133
Element 140
Generation 145
Summary 148
Chapter 5: Nondeferred Operators 151
Referenced Namespaces 151
Common Classes 151
The Nondeferred Operators by Purpose 154
Conversion 155
Equality 168
Element 172
Quantifiers 187
Aggregate 193
Summary 209
Part 3: LINQ to XML 211
Chapter 6: LINQ to XML Introduction 213
Introduction 215
Cheating the W3C DOM XML API 216
Summary 217
Chapter 7: The LINQ to XML API 219
Referenced Namespaces 219
Significant API Design Enhancements 219
XML Tree Construction Simplified with Functional Construction 220
Document Centricity Eliminated in Favor of Element Centricity 222
Names, Namespaces, and Prefixes 224
Node Value Extraction 227
The LINQ to XML Object Model 230
CONTENTS
Deferred Query Execution, Node Removal, and the Halloween Problem 231
XML Creation 234
Creating Elements with XEIement 234
Creating Attributes with XAttribute 237
Creating Comments with XComment 238
Creating Containers with XContainer 238
Creating Declarations with XDeclaration 239
Creating Document Types with XDocumentType 240
Creating Documents with XDocument 241
Creating Names with XName 242
Creating Namespaces with XNamespace 243
Creating Nodes with XNode 243
Creating Processing Instructions with XProcessinglnstruction 243
Creating Streaming Elements with XStreamingElement 246
Creating Text with XText 247
Creating CData with XCData 248
XML Output 248
Saving with XDocument.Save() 248
Saving with XEIement.Save() 250
XML Input 251
Loading with XDocument.Load() 251
Loading with XEIement.Load() 253
Parsing with XDocument.Parse() or XEIement.Parse() 254
XML Traversal 254
Traversal Properties 255
Traversal Methods 260
XML Modification 276
Adding Nodes 276
Deleting Nodes 281
Updating Nodes 284
ix
CONTENTS
XEIement.SetElementValue() on Child XEIement Objects 289
XML Attributes •290
Attribute Creation 291
Attribute Traversal • 291
Attribute Modification 295
XML Annotations 300
Adding Annotations with XObject.AddAnnotation() 300
Accessing Annotations with XObject.Annotation() or XObject.Annotations() 300
Removing Annotations with XObject.RemoveAnnotations() 301
Annotations Example 301
XML Events 304
XObjectChanging 305
XObjectChanged 305
A Couple of Event Examples 306
Trick or Treat, or Undefined? 310
Summary 310
Chapter 8: LINQ to XML Operators 313
Introduction to LINQ to XML Operators 313
Ancestors 314
Prototypes 314
Examples 314
AncestorsAndSelf 319
Prototypes 319
Examples 319
Attributes 322
Prototypes 322
Examples 322
DescendantNodes 324
Prototypes 324
Examples 325
CONTENTS
DescendantNodesAndSelf 326
Prototypes 326
Examples 327
Descendants 328
Prototypes 328
Examples 329
DescendantsAndSelf 331
Prototypes 331
Examples 331
Elements 334
Prototypes 334
Examples 334
InDocumentOrder 336
Prototypes 337
Examples 337
Nodes 338
Prototypes 338
Examples 339
Remove .340
Prototypes 340
Examples 340
Summary 343
Chapter 9: Additional XML Capabilities 345
Referenced Namespaces ,
345
Queries 346
No Reaching 346
A Complex Query 348
Transformations 355
Transformations Using XSLT 355
Transformations Using Functional Construction 357
CONTENTS
Tips359
Validation... 366
The Extension Methods 366
Prototypes367
Obtaining an XML Schema 368
Examples 370
XPath •383
Prototypes 383
Examples 384
Summary 384
Part 4: LINQ to DataSet.. 387
Chapter 10: LINQ to DataSet Operators 389
Assembly References 390
Referenced Namespaces 390
Common Code for the Examples 390
DataRow Set Operators 392
Distinct 392
Except 396
Intersect 399
Union 401
SequenceEqual 403
DataRow Field Operators 405
Field<T> 410
SetField<T> 415
DataTable Operators 419
AsEnumerable 419
CopyToDataTable<DataRow> 419
Summary 425
Chapter 11: Additional DataSet Capabilities 427
Required Namespaces,
427
xii
CONTENTS
Typed DataSets 427
Putting It All Together 429
Summary 432
Part 5: LINQ to SQL 435
Chapter 12: LINQ to SQL Introduction . 437
Introducing LINQ to SQL 438
The DataContext 439
Entity Classes 440
Associations 440
Concurrency Conflict Detection 441
Concurrency Conflict Resolution 441
Prerequisites for Running the Examples 442
Obtaining the Appropriate Version of the Northwind Database 442
Generating the Northwind Entity Classes 442
Generating the Northwind XML Mapping File 444
Using the LINQ to SQL API 444
IQueryable<T> 444
Some Common Methods 444
GetStringFromDb() 445
ExecuteStatementlnDbO 446
Summary 447
Chapter 13: LINQ to SQL Tips and Tools 449
Introduction to LINQ to SQL Tips and Tools 449
Tips 449
Use the DataContextlog Property 450
Use the GetChangeSet() Method 451
Consider Using Partial Classes or Mapping Files 451
Consider Using Partial Methods 451
Tools 452
SQLMetal 452
xiii
CONTENTS
The Object Relational Designer 41)0
Use SQLMetal and the O/R Designer Together 472
Summary -473
Chapter 14: LINQ to SQL Database Operations 475
Prerequisites for Running the Examples 475
Some Common Methods 475
Using the LINQ to SQL API 476
Standard Database Operations 476
Inserts 4?6
Queries 480
Updates 506
Deletes 510
Overriding Database Modification Statements 513
Overriding the Insert Method 513
Overriding the Update Method 514
Overriding the Delete Method 514
Example 514
Overriding in the Object Relational Designer 517
Considerations 517
SQL Translation 517
Summary 520
Chapter 15: LINQ to SQL Entity Classes 521
Prerequisites for Running the Examples 521
Entity Classes 521
Creating Entity Classes 521
XML External Mapping File Schema 552
Projecting into Entity Classes vs. Nonentity Classes 552
Extending Entity Classes with Partial Methods 558
Important System.Data.Linq API Classes 560
xiv
CONTENTS
EntitySet<T> 560
EntityRef<T> 560
Table<T> 563
lExecuteResult 564
ISingleResult<T> 565
IMultipleResults 565
Summary 567
Chapter 16: The LINQ to SQL DataContext 569
Prerequisites for Running the Examples 569
Some Common Methods 569
Using the LINQ to SQL API 569
[Your]DataContext Class 569
The DataContext Class 570
The DataContext Class Implements IDisposable 573
Primary Purposes 573
The Data Context Lifetime 580
DataContext() and [Your]DataContext() 580
SubmitChangesO 594
DatabaseExists() 602
CreateDatabase() 603
DeleteDatabase() 604
CreateMethodCallQuery() 605
ExecuteQuery() 607
Translate!) 610
ExecuteCommandO 612
ExecuteMethodCall() 613
GetCommand() 621
GetChangeSetO 623
GetTable() 625
RefreshO 626
Summary 634
XV
CONTENTS
Chapter 17: LINQ to SQL Concurrency Conflicts.... 635
Prerequisites for Running the Examples 635
Some Common Methods 635
Using the LINQ to SQL API 635
Concurrency Conflicts 635
Optimistic Concurrency 636
Pessimistic Concurrency 647
An Alternative Approach for Middle Tiers and Servers 650
Summary - 652
Chapter 18: Additional UNQ to SQL Capabilities 653
Prerequisites for Running the Examples 653
Using the LINQ to SQL API 653
Using the LINQ to XML API 653
Database Views 653
Entity Class Inheritance 655
Transactions 661
Summary 663
Part 6: LINQ to Entities 665
Chapter 19: LINQ to Entities Introduction 667
Introducing LINQ to Entities 668
The ObjectContext 669
Entity Classes 669
Associations 670
Prerequisites for Running the Examples 670
Obtaining the Appropriate Version of the Northwind Database 670
Generating the Northwind Entity Data Model 670
Using the LINQ to Entities API 674
IQueryable<T> 674
Some Common Methods,
675
xvi
CONTENTS
GetStringFromDb() 675
ExecuteStatementlnDb() 676
Summary 677
Chapter 20: LINQ to Entities Operations .679
Prerequisites for Running the Examples 679
Some Common Methods 679
Standard Database Operations 680
Inserts 680
Queries 687
Updates 704
Deletes ...705
Managing Concurrency 715
Enabling Concurrency Checks 716
Handling Concurrency Conflicts 717
Summary 722
Chapter 21: LINQ to Entities Classes 723
Prerequisites for Running the Examples 723
The ObjectContext Class 723
Constructor 724
DatabaseExists() 726
DeleteDatabase() 726
CreateDatabase() 727
SaveChanges() 727
RefreshO 728
AddObject() 729
CreateObject() 730
DeleteObject() 731
EntityObject 732
Constructor 732
Factory Method 733
xvii
CONTENTS
Primitive Properties 735
Navigation Properties 737
EntityReference 740
Load() 740
Value 741
EntityCollection 741
AddO 741
Remove() 743
ClearO 745
ContainsO 745
Load() 747
Count 747
Summary 748
Part 7: Parallel LINQ 749
Chapter 22: Parallel LINQ Introduction 751
Introducing Parallel LINQ 751
Parallel LINQ Is for Objects 756
Using the LINQ to Entities API 756
Summary 756
Chapter 23: Using Parallel LINQ 757
Creating a Parallel LINQ Query 757
Preserving Result Ordering 760
Controlling Parallelism 763
Forcing Parallel Execution 763
Limiting the Degree of Parallelism 764
Dealing with Exceptions 764
Queries Without Results 768
Creating Ranges and Repetitions 770
Summary 771
xviii
CONTENTS
Chapter 24: Parallel LINQ Operators .773
ParallelQuery Creation Operators 773
AsParallel 773
Range 777
Repeat 778
Empty 779
Execution Control Operators 779
AsOrdered 779
AsUnordered 782
AsSequential 783
AsEnumerable 784
WithDegreeOfParallelism 785
WithExecutionMode 786
WithMergeOptions 787
Conversion Operators 790
Cast 790
OtType 791
The ForAII Operator 792
Prototypes 792
Examples 792
Summary 793
Index 795
xix