Pro LINQ: Language Integrated Query in C# 2010

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

LINQ is the part of the .NET Framework that provides a generic approach to querying data from different data sources. It has quickly become the next must-have skill for .NET developers. Pro LINQ: Language Integrated Query in C# 2010 is all about code. Literally, this book starts with code and ends with code. Most books show the simplest examples of how to use a method, but they so rarely show how to use the more complex prototypes. This book is different. Demonstrating the overwhelming majority of LINQ operators and prototypes, it is a veritable treasury of LINQ examples. Rather than obscure the relevant LINQ principles in code examples by focusing on a demonstration application you have no interest in writing, this book cuts right to the chase of each LINQ operator, method, or class. However, where complexity is necessary to truly demonstrate an issue, the examples are right there in the thick of it. For example, code samples demonstrating how to handle concurrency conflicts actually create concurrency conflicts so you can step through the code and see them unfold. Face it, most technical books, while informative, are dull. LINQ need not be dull. Written with a sense of humor, this book will attempt to entertain you on your journey through the wonderland of LINQ and C# 2010.

Author(s): Joseph Rattz; Adam Freeman
Publisher: Apress
Year: 2010

Language: English
Pages: 840

Prelim
Contents at a Glance
Contents
About the Authors
About the Technical Reviewer
Acknowledgments
Pro LINQ: Language Integrated Query in C# 2010
Hello LINQ
A Paradigm Shift
Query XML
Query a SQL Server Database
Introduction
LINQ Is About Data Queries
LINQ to Objects
LINQ to XML
LINQ to DataSet
LINQ to SQL
LINQ to Entities
How to Obtain LINQ
LINQ Is Not Just for Queries
Tips to Get You Started
Use the var Keyword When Confused
Use the Cast or OfType Operators for Legacy Collections
The OfType Operator versus the Cast Operator
Don’t Assume a Query Is Bug-Free
Take Advantage of Deferred Queries
Use the DataContext Log
Use the LINQ Forum
Summary
C# Language Enhancements for LINQ
C# Language Additions
Lambda Expressions
Using Named Methods
Using Anonymous Methods
Using Lambda Expressions
Expression Trees
Keyword var, Object Initialization, and Anonymous Types
The Implicitly Typed Local Variable Keyword var
Object and Collection Initialization Expressions
Anonymous Types
Extension Methods
Instance (Object) vs. Static (Class) Methods Recap
The Problem Solved by Extension Methods
The Solution
Extension Method Declarations and Invocations
Extension Method Precedence
Partial Methods
A Partial Method Example
What Is the Point of Partial Methods?
The Rules
Query Expressions
Query Expression Grammar
Query Expression Translation
Summary
LINQ to Objects
LINQ to Objects Introduction
LINQ to Objects Overview
IEnumerable, Sequences, and the Standard Query Operators
Returning IEnumerable, Yielding, and Deferred Queries
Func Delegates
The Standard Query Operators Alphabetical Cross-Reference
A Tale of Two Syntaxes
Summary
Deferred Operators
Referenced Namespaces
Referenced Assemblies
Common Classes
The Deferred Operators by Purpose
Restriction
Where
Projection
Select
SelectMany
Partitioning
Take
TakeWhile
Skip
SkipWhile
Concatenation
Concat
Ordering
OrderBy
OrderByDescending
ThenBy
ThenByDescending
Reverse
Join
GroupJoin
Grouping
GroupBy
Set
Distinct
Union
Intersect
Except
Conversion
Cast
OfType
AsEnumerable
Element
DefaultIfEmpty
Generation
Range
Repeat
Empty
Summary
Nondeferred Operators
Referenced Namespaces
Common Classes
The Nondeferred Operators by Purpose
Conversion
ToArray
ToList
ToDictionary
ToLookup
Equality
SequenceEqual
Element
First
FirstOrDefault
Last
LastOrDefault
Single
SingleOrDefault
ElementAt
ElementAtOrDefault
Quantifiers
Any
All
Contains
Aggregate
Count
LongCount
Sum
Min
Max
Average
Aggregate
Summary
LINQ to XML
LINQ to XML Introduction
Introduction
Cheating the W3C DOM XML API
Summary
The LINQ to XML API
Referenced Namespaces
Significant API Design Enhancements
XML Tree Construction Simplified with Functional Construction
Document Centricity Eliminated in Favor of Element Centricity
Names, Namespaces, and Prefixes
Node Value Extraction
The LINQ to XML Object Model
Deferred Query Execution, Node Removal, and the Halloween Problem
XML Creation
Creating Elements with XElement
Creating Attributes with XAttribute
Creating Comments with XComment
Creating Containers with XContainer
Creating Declarations with XDeclaration
Creating Document Types with XDocumentType
Creating Documents with XDocument
Creating Names with XName
Creating Namespaces with XNamespace
Creating Nodes with XNode
Creating Processing Instructions with XProcessingInstruction
Creating Streaming Elements with XStreamingElement
Creating Text with XText
Creating CData with XCData
XML Output
Saving with XDocument.Save()
Saving with XElement.Save()
XML Input
Loading with XDocument.Load()
Loading with XElement.Load()
Parsing with XDocument.Parse() or XElement.Parse()
XML Traversal
Traversal Properties
Forward with XNode.NextNode
Backward with XNode.PreviousNode
Up to Document with XObject.Document
Up with XObject.Parent
Traversal Methods
Down with XContainer.Nodes()
Down with XContainer.Elements()
Down with XContainer.Element()
Up Recursively with XNode.Ancestors()
Up Recursively with XElement.AncestorsAndSelf()
Down Recursively with XContainer.Descendants()
Down Recursively with XElement.DescendantsAndSelf()
Forward with XNode.NodesAfterSelf()
Forward with XNode.ElementsAfterSelf()
Backward with XNode.NodesBeforeSelf()
Backward with XNode.ElementsBeforeSelf()
XML Modification
Adding Nodes
XContainer.Add() (AddLast)
XContainer.AddFirst()
XNode.AddBeforeSelf()
XNode.AddAfterSelf()
Deleting Nodes
XNode.Remove()
IEnumerable.Remove()
XElement.RemoveAll()
Updating Nodes
XElement.Value on XElement Objects, XText.Value on XText Objects, and XComment.Value on XComment Objects
XDocumentType.Name, XDocumentType.PublicId, XDocumentType.SystemId, and XDocumentType.InternalSubset on XDocumentType Objects
XProcessingInstruction.Target on XProcessingInstruction Objects and XProcessingInstruction.Data on XProcessingInstruction Object
XElement.ReplaceAll()
XElement.SetElementValue() on Child XElement Objects
XML Attributes
Attribute Creation
Attribute Traversal
Forward with XElement.FirstAttribute
Forward with XAttribute.NextAttribute
Backward with XAttribute.PreviousAttribute
Backward with XElement.LastAttribute
XElement.Attribute()
XElement.Attributes()
Attribute Modification
Adding Attributes
Deleting Attributes
Updating Attributes
XElement.SetAttributeValue()
XML Annotations
Adding Annotations with XObject.AddAnnotation()
Accessing Annotations with XObject.Annotation() or XObject.Annotations()
Removing Annotations with XObject.RemoveAnnotations()
Annotations Example
XML Events
XObject.Changing
XObject.Changed
A Couple of Event Examples
Trick or Treat, or Undefined?
Summary
LINQ to XML Operators
Introduction to LINQ to XML Operators
Ancestors
Prototypes
Examples
AncestorsAndSelf
Prototypes
Examples
Attributes
Prototypes
Examples
DescendantNodes
Prototypes
Examples
DescendantNodesAndSelf
Prototypes
Examples
Descendants
Prototypes
Examples
DescendantsAndSelf
Prototypes
Examples
Elements
Prototypes
Examples
InDocumentOrder
Prototypes
Examples
Nodes
Prototypes
Examples
Remove
Prototypes
Examples
Summary
Additional XML Capabilities
Referenced Namespaces
Queries
No Reaching
A Complex Query
Transformations
Transformations Using XSLT
Transformations Using Functional Construction
Tips
Simplify Complex Tasks with Helper Methods
Suppressing Node Construction with null
Handling Multiple Peer Nodes While Remaining Flat
Validation
The Extension Methods
Prototypes
Obtaining an XML Schema
Examples
XPath
Prototypes
Examples
Summary
LINQ to DataSet
LINQ to DataSet Operators
Assembly References
Referenced Namespaces
Common Code for the Examples
DataRow Set Operators
Distinct
Prototypes
Examples
Except
Prototypes
Examples
Intersect
Prototypes
Examples
Union
Prototypes
Examples
SequenceEqual
Prototypes
Examples
DataRow Field Operators
Field
Prototypes
Examples
SetField
Prototypes
Examples
DataTable Operators
AsEnumerable
Prototypes
Examples
CopyToDataTable
Prototypes
Examples
Summary
Additional DataSet Capabilities
Required Namespaces
Typed DataSets
Putting It All Together
Summary
LINQ to SQL
LINQ to SQL Introduction
Introducing LINQ to SQL
The DataContext
Entity Classes
Associations
Concurrency Conflict Detection
Concurrency Conflict Resolution
Prerequisites for Running the Examples
Obtaining the Appropriate Version of the Northwind Database
Generating the Northwind Entity Classes
Generating the Northwind XML Mapping File
Using the LINQ to SQL API
IQueryable
Some Common Methods
GetStringFromDb()
ExecuteStatementInDb()
Summary
LINQ to SQL Tips and Tools
Introduction to LINQ to SQL Tips and Tools
Tips
Use the DataContext.Log Property
Use the GetChangeSet() Method
Consider Using Partial Classes or Mapping Files
Consider Using Partial Methods
Tools
SQLMetal
XML Mapping File Vs. DBML Intermediate File
Working with DBML Intermediate Files
The Object Relational Designer
Creating Your LINQ to SQL Classes File
Connecting the DataContext to the Database
Adding an Entity Class
Editing the Entity Class Model
Adding Objects to the Entity Class Model
Overriding the Insert, Update, and Delete Methods
Use SQLMetal and the O/R Designer Together
Summary
LINQ to SQL Database Operations
Prerequisites for Running the Examples
Some Common Methods
Using the LINQ to SQL API
Standard Database Operations
Inserts
Inserting Attached Entity Objects
Queries
Exceptions to the Norm
Associations
Joins
Deferred Query Execution
The SQL IN Statement with the Contains Operator
Updates
Updating Associated Classes
Deletes
Deleting Attached Entity Objects
Deleting Relationships
Overriding Database Modification Statements
Overriding the Insert Method
Overriding the Update Method
Overriding the Delete Method
Example
Overriding in the Object Relational Designer
Considerations
SQL Translation
Summary
LINQ to SQL Entity Classes
Prerequisites for Running the Examples
Entity Classes
Creating Entity Classes
Generating Entity Classes
Writing Entity Classes by Hand
Entity Class Attributes and Attribute Properties
XML External Mapping File Schema
Projecting into Entity Classes vs. Nonentity Classes
Prefer Object Initialization to Parameterized Construction When Projecting
Extending Entity Classes with Partial Methods
Important System.Data.Linq API Classes
EntitySet
EntityRef
Entity
HasLoadedOrAssignedValue
Table
IExecuteResult
ReturnValue
GetParameterValue
ISingleResult
ReturnValue
IMultipleResults
ReturnValue
GetResult
Summary
The LINQ to SQL DataContext
Prerequisites for Running the Examples
Some Common Methods
Using the LINQ to SQL API
[Your]DataContext Class
The DataContext Class
The DataContext Class Implements IDisposable
Primary Purposes
Identity Tracking
Change Tracking
Change Processing
The Data Context Lifetime
DataContext() and [Your]DataContext()
Prototypes
Examples
SubmitChanges()
Prototypes
Examples
DatabaseExists()
Prototypes
Examples
CreateDatabase()
Prototypes
Examples
DeleteDatabase()
Prototypes
Examples
CreateMethodCallQuery()
Prototypes
Examples
ExecuteQuery()
Prototypes
Examples
Translate()
Prototypes
Examples
ExecuteCommand()
Prototypes
Examples
ExecuteMethodCall()
Prototypes
Examples
GetCommand()
Prototypes
Examples
GetChangeSet()
Prototypes
Examples
GetTable()
Prototypes
Examples
Refresh()
Prototypes
Examples
Summary
LINQ to SQL Concurrency Conflicts
Prerequisites for Running the Examples
Some Common Methods
Using the LINQ to SQL API
Concurrency Conflicts
Optimistic Concurrency
Conflict Detection
Conflict Resolution
Pessimistic Concurrency
An Alternative Approach for Middle Tiers and Servers
Summary
Additional LINQ to SQL Capabilities
Prerequisites for Running the Examples
Using the LINQ to SQL API
Using the LINQ to XML API
Database Views
Entity Class Inheritance
Transactions
Summary
LINQ to Entities
LINQ to Entities Introduction
Introducing LINQ to Entities
The ObjectContext
Entity Classes
Associations
Prerequisites for Running the Examples
Obtaining the Appropriate Version of the Northwind Database
Generating the Northwind Entity Data Model
Using the LINQ to Entities API
IQueryable
Some Common Methods
GetStringFromDb()
ExecuteStatementInDb()
Summary
LINQ to Entities Operations
Prerequisites for Running the Examples
Some Common Methods
Standard Database Operations
Inserts
Creating Partially Populated Entity Types
Inserting Attached Entity Objects
Queries
Basic Queries
Compiled Queries
Seeing the SQL Statement
Loading Related Objects
Querying Views
Querying Stored Procedures
Joins
Updates
Updating Associated Objects
Deletes
Deleting Related Objects
Managing Concurrency
Enabling Concurrency Checks
Handling Concurrency Conflicts
Summary
LINQ to Entities Classes
Prerequisites for Running the Examples
The ObjectContext Class
Constructor
Prototypes
Examples
DatabaseExists()
Prototypes
Examples
DeleteDatabase()
Prototypes
Examples
CreateDatabase()
Prototypes
Examples
SaveChanges()
Prototypes
Examples
Refresh()
Prototypes
Examples
AddObject()
Prototypes
Examples
CreateObject()
Prototypes
Examples
DeleteObject()
Prototypes
Examples
EntityObject
Constructor
Prototypes
Examples
Factory Method
Prototypes
Examples
Primitive Properties
Prototypes
Examples
Navigation Properties
Prototypes
Examples
EntityReference
Load()
Examples
Value
EntityCollection
Add()
Prototypes
Examples
Remove()
Prototypes
Examples
Clear()
Prototypes
Examples
Contains()
Prototypes
Examples
Load()
Count
Prototypes
Examples
Summary
Parallel LINQ
Parallel LINQ Introduction
Introducing Parallel LINQ
Parallel LINQ Is for Objects
Using the LINQ to Entities API
Summary
Using Parallel LINQ
Creating a Parallel LINQ Query
Preserving Result Ordering
Controlling Parallelism
Forcing Parallel Execution
Limiting the Degree of Parallelism
Dealing with Exceptions
Queries Without Results
Creating Ranges and Repetitions
Summary
Parallel LINQ Operators
ParallelQuery Creation Operators
AsParallel
Prototypes
Examples
Range
Prototypes
Examples
Repeat
Prototypes
Examples
Empty
Prototypes
Execution Control Operators
AsOrdered
Prototypes
Examples
AsUnordered
Prototypes
Examples
AsSequential
Prototypes
Examples
AsEnumerable
Prototypes
Examples
WithDegreeOfParallelism
Prototypes
Examples
WithExecutionMode
Prototypes
Examples
WithMergeOptions
Prototypes
Examples
Conversion Operators
Cast
Prototypes
Examples
OfType
Prototypes
Examples
The ForAll Operator
Prototypes
Examples
Summary
Index
¦ ¦ ¦ ¦ Special Characters
¦ A
¦ B
¦
C
¦ D
¦ E
¦ F
¦ H
¦ I
¦ G
¦ J
¦ K
¦ L
¦ M
¦ N
¦ O
¦ P
¦ R
¦ Q
¦ S
¦ T
¦ U
¦ V
¦ W
¦
X
¦ Y