Programming Microsoft® LINQ in Microsoft .NET Framework 4

Book description

Dig into LINQ -- and transform the way you work with data.

With LINQ, you can query data from a variety of sources -- including databases, objects, and XML files -- directly from Microsoft Visual Basic or C#. Guided by data-access experts who've worked in depth with LINQ and the Microsoft development teams, you'll learn how .NET Framework 4 implements LINQ, and how to exploit it. Clear examples show you how to deliver your own data-access solutions faster and with leaner code.

Discover how to:

  • Use LINQ to query databases, object collections, arrays, XML, Microsoft Excel files, and other sources

  • Apply LINQ best practices to build data-enabled .NET applications and services

  • Manipulate data in a relational database with ADO.NET Entity Framework or LINQ to SQL

  • Read, write, and manage XML content more efficiently with LINQ to XML

  • Extend LINQ to support additional data sources by creating custom operators and providers

  • Examine other implementations, such as LINQ to SharePoint

  • Use LINQ within the data, business, and service layers of a distributed application

  • Get code samples on the Web

  • Table of contents

    1. Programming Microsoft® LINQ in Microsoft .NET Framework 4
    2. Dedication
    3. Preface
    4. Acknowledgments
    5. Introduction
      1. Who Is This Book For?
      2. Organization of This Book
      3. Conventions and Features in This Book
      4. System Requirements
      5. The Companion Website
      6. Find Additional Content Online
      7. Errata & Book Support
      8. We Want to Hear from You
      9. Stay in Touch
    6. I. LINQ Foundations
      1. 1. LINQ Introduction
        1. What Is LINQ?
        2. Why Do We Need LINQ?
        3. How LINQ Works
          1. Relational Model vs. Hierarchical/Network Model
          2. XML Manipulation
        4. Language Integration
          1. Declarative Programming
          2. Type Checking
          3. Transparency Across Different Type Systems
        5. LINQ Implementations
          1. LINQ to Objects
          2. LINQ to ADO.NET
          3. LINQ to XML
        6. Summary
      2. 2. LINQ Syntax Fundamentals
        1. LINQ Queries
          1. Query Syntax
          2. Full Query Syntax
        2. Query Keywords
          1. From Clause
          2. Where Clause
          3. Select Clause
          4. Group and Into Clauses
          5. Orderby Clause
          6. Join Clause
          7. Let Clause
          8. Additional Visual Basic Keywords
        3. Deferred Query Evaluation and Extension Method Resolution
          1. Deferred Query Evaluation
          2. Extension Method Resolution
        4. Some Final Thoughts About LINQ Queries
          1. Degenerate Query Expressions
          2. Exception Handling
        5. Summary
      3. 3. Linq to Objects
        1. Query Operators
          1. The Where Operator
          2. Projection Operators
            1. Select
            2. SelectMany
          3. Ordering Operators
            1. OrderBy and OrderByDescending
            2. ThenBy and ThenByDescending
            3. Reverse Operator
          4. Grouping Operators
          5. Join Operators
            1. Join
            2. GroupJoin
          6. Set Operators
            1. Distinct
            2. Union, Intersect, and Except
            3. Zip
          7. Aggregate Operators
            1. Count and LongCount
            2. Sum
            3. Min and Max
            4. Average
            5. Aggregate
          8. Aggregate Operators in Visual Basic
          9. Generation Operators
            1. Range
            2. Repeat
            3. Empty
          10. Quantifier Operators
            1. Any
            2. All
            3. Contains
          11. Partitioning Operators
            1. Take
            2. TakeWhile
            3. Skip and SkipWhile
          12. Element Operators
            1. First
            2. FirstOrDefault
            3. The Last and LastOrDefault
            4. Single
            5. SingleOrDefault
            6. ElementAt and ElementAtOrDefault
            7. DefaultIfEmpty
          13. Other Operators
            1. Concat
            2. SequenceEqual
        2. Conversion Operators
          1. AsEnumerable
          2. ToArray and ToList
          3. ToDictionary
          4. ToLookup
          5. OfType and Cast
        3. Summary
    7. II. LINQ to Relational
      1. 4. Choosing Between LINQ to SQL and LINQ to Entities
        1. Comparison Factors
        2. When to Choose LINQ to Entities and the Entity Framework
        3. When to Choose LINQ to SQL
        4. Other Considerations
        5. Summary
      2. 5. LINQ to SQL: Querying Data
        1. Entities in LINQ to SQL
          1. External Mapping
        2. Data Modeling
          1. DataContext
          2. Entity Classes
          3. Entity Inheritance
          4. Unique Object Identity
          5. Entity Constraints
          6. Associations Between Entities
            1. EntityRef
            2. EntitySet
            3. Graph Consistency
          7. Relational Model vs. Hierarchical Model
        3. Data Querying
          1. Projections
          2. Stored Procedures and User-Defined Functions
            1. Stored Procedures
            2. User-Defined Functions
          3. Compiled Queries
          4. Different Approaches to Querying Data
          5. Direct Queries
          6. Deferred Loading of Entities
          7. Deferred Loading of Properties
          8. Read-Only DataContext Access
          9. Limitations of LINQ to SQL
            1. Aggregate Operators
            2. Partitioning Operators
            3. Element Operators
            4. String Methods
            5. DateTime Methods
            6. LIKE Operator
            7. Unsupported SQL Functionalities
        4. Thinking in LINQ to SQL
          1. The IN/EXISTS Clause
          2. SQL Query Reduction
          3. Mixing .NET Code with SQL Queries
        5. Summary
      3. 6. LINQ to SQL: Managing Data
        1. CRUD and CUD Operations
          1. Entity Updates
            1. Cascading Deletes and Updates
            2. Entity States
            3. Entity Synchronization
          2. Database Updates
            1. Overriding SubmitChanges
          3. Customizing Insert, Update, and Delete
            1. Stored Procedures
            2. Intercepting Insert, Update, and Delete Operations
        2. Database Interaction
          1. Concurrent Operations
            1. Column Attributes for Concurrency Control
          2. Transactions
          3. Exceptions
            1. DataContext Construction
            2. Database Reads
            3. Database Writes
            4. Entity Manipulation
        3. Databases and Entities
          1. Entity Attributes to Maintain Valid Relationships
          2. Deriving Entity Classes
          3. Attaching Entities
            1. Entity Serialization
            2. Attach Operation
          4. Binding Metadata
            1. External XML Mapping File
            2. Creating a Database from Entities
            3. Creating Entities from a Database
          5. Differences Between the .NET Framework and SQL Type Systems
        4. Summary
      4. 7. LINQ to SQL: Modeling Data and Tools
        1. File Types
          1. DBML—Database Markup Language
          2. C# and Visual Basic Source Code
          3. XML—External Mapping File
          4. LINQ to SQL File Generation
            1. Generating a DBML File from an Existing Database
            2. Generating an Entity’s Source Code with Attribute-Based Mapping
            3. Generating an Entity’s Source Code with an External XML Mapping File
            4. Creating a DBML File from Scratch
        2. SQLMetal
          1. Generating a DBML File from a Database
          2. Generating Source Code and a Mapping File from a Database
          3. Generating Source Code and a Mapping File from a DBML File
        3. Using the Object Relational Designer
          1. DataContext Properties
          2. Entity Class
            1. Entity Members
          3. Association Between Entities
            1. One-to-One Relationships
          4. Entity Inheritance
          5. Stored Procedures and User-Defined Functions
            1. Return Type of Data Function
            2. Mapping to Delete, Insert, and Update Operations
          6. Views and Schema Support
        4. Summary
      5. 8. LINQ to Entities: Modeling Data with Entity Framework
        1. The Entity Data Model
          1. Generating a Model from an Existing Database
          2. Starting from an Empty Model
          3. Generated Code
          4. Entity Data Model (.edmx) Files
        2. Associations and Foreign Keys
        3. Complex Types
        4. Inheritance and Conditional Mapping
        5. Modeling Stored Procedures
          1. Non-CUD Stored Procedures
          2. CUD Stored Procedures
        6. POCO Support
        7. T4 Templates
        8. Summary
      6. 9. LINQ to Entities: Querying Data
        1. EntityClient Managed Providers
        2. LINQ to Entities
          1. Selecting Single Entities
          2. Unsupported Methods and Keywords
          3. Canonical and Database Functions
          4. User-Defined Functions
          5. Stored Procedures
        3. ObjectQuery<T> and ObjectContext
          1. Lazy Loading
          2. Include
          3. Load and IsLoaded
          4. The LoadProperty Method
          5. MergeOption
          6. The ToTraceString Method
          7. ExecuteStoreCommand and ExecuteStoreQuery
          8. The Translate<T> Method
        4. Query Performance
          1. Pre-Build Store Views
          2. EnablePlanCaching
          3. Pre-Compiled Queries
          4. Tracking vs. No Tracking
        5. Summary
      7. 10. LINQ to Entities: Managing Data
        1. Managing Entities
          1. Adding a New Entity
          2. Updating an Entity
          3. Deleting an Entity
          4. Using SaveChanges
          5. Cascade Add/Update/Delete
          6. Managing Relationships
        2. Using ObjectStateManager and EntityState
          1. DetectChanges and AcceptAllChanges
          2. ChangeObjectState and ChangeRelationshipState
          3. ObjectStateManagerChanged
          4. EntityKey
          5. GetObjectByKey and TryGetObjectByKey
        3. Managing Concurrency Conflicts
        4. Managing Transactions
        5. Detaching, Attaching, and Serializing Entities
          1. Detaching Entities
          2. Attaching Entities
          3. ApplyOriginalValues and ApplyCurrentValues
          4. Serializing Entities
        6. Using Self-Tracking Entities
        7. Summary
      8. 11. LINQ to DataSet
        1. Introducing LINQ to DataSet
        2. Using LINQ to Load a DataSet
          1. Loading a DataSet with LINQ to SQL
          2. Loading Data with LINQ to DataSet
        3. Using LINQ to Query a DataSet
          1. Understanding DataTable.AsEnumerable
          2. Creating DataView Instances with LINQ
          3. Using LINQ to Query a Typed DataSet
          4. Accessing Untyped DataSet Data
          5. Comparing DataRow Instances
        4. Summary
    8. III. LINQ to XML
      1. 12. LINQ to XML: Managing the XML Infoset
        1. Introducing LINQ to XML
        2. LINQ to XML Programming
          1. XDocument
          2. XElement
          3. XAttribute
          4. XNode
          5. XName and XNamespace
          6. Other X* Classes
          7. XStreamingElement
          8. XObject and Annotations
        3. Reading, Traversing, and Modifying XML
        4. Summary
      2. 13. LINQ to XML: Querying Nodes
        1. Querying XML
          1. Attribute, Attributes
          2. Element, Elements
          3. XPath Axes “Like” Extension Methods
          4. XNode Selection Methods
          5. InDocumentOrder
        2. Understanding Deferred Query Evaluation
        3. Using LINQ Queries over XML
          1. Querying XML Efficiently to Build Entities
        4. Transforming XML with LINQ to XML
        5. Support for XSD and Validation of Typed Nodes
        6. Support for XPath and System.Xml.XPath
        7. Securing LINQ to XML
        8. Serializing LINQ to XML
        9. Summary
    9. IV. Advanced LINQ
      1. 14. Inside Expression Trees
        1. Lambda Expressions
        2. What Is an Expression Tree?
          1. Creating Expression Trees
          2. Encapsulation
          3. Immutability and Modification
        3. Dissecting Expression Trees
          1. The Expression Class
          2. Expression Tree Node Types
            1. ExpressionType Enumeration
            2. Classes Derived from Expression
          3. Practical Nodes Guide
            1. LambdaExpression and ParameterExpression
            2. BinaryExpression
            3. ConstantExpression
            4. MethodCallExpression
            5. ConditionalExpression
            6. InvocationExpression
        4. Visiting an Expression Tree
        5. Dynamically Building an Expression Tree
          1. How the Compiler Generates an Expression Tree
          2. Combining Existing Expression Trees
          3. Dynamic Composition of an Expression Tree
        6. Summary
      2. 15. Extending LINQ
        1. Custom Operators
        2. Specialization of Existing Operators
          1. Dangerous Practices
          2. Limits of Specialization
        3. Creating a Custom LINQ Provider
          1. The IQueryable Interface
          2. From IEnumerable to IQueryable and Back
          3. Inside IQueryable and IQueryProvider
          4. Writing the FlightQueryProvider
            1. The FlightStatusService Class
            2. Implementing IQueryable in FlightQuery
            3. Implementing IQueryProvider in FlightQueryProvider
            4. Implementing an ExpressionVisitor in FlightQueryTranslator
            5. Working with the FlightQueryProvider
            6. Cost-Benefit Balance of a Custom LINQ Provider
        4. Summary
      3. 16. Parallelism and Asynchronous Processing
        1. Task Parallel Library
          1. The Parallel.For and Parallel.ForEach Methods
          2. The Parallel.Invoke Method
          3. The Task Class
          4. The Task<TResult> Class
          5. Controlling Task Execution
          6. Using Tasks for Asynchronous Operations
          7. Concurrency Considerations
            1. Race Conditions
            2. Concurrent Collections
            3. Task Synchronization
        2. PLINQ
          1. Threads Used by PLINQ
          2. Implementing PLINQ
          3. Consuming the Result of a PLINQ Query
            1. Pipelined Processing
            2. Stop-and-Go Processing
            3. Inverted Enumeration
          4. Controlling Result Order in PLINQ
          5. Processing Query Results
          6. Handling Exceptions with PLINQ
          7. Canceling a PLINQ Query
          8. Controlling Execution of a PLINQ Query
          9. Changes in Data During Execution
          10. PLINQ and Other LINQ Implementations
        3. Reactive Extensions for .NET
        4. Summary
      4. 17. Other LINQ Implementations
        1. Database Access and ORM
        2. Data Access Without a Database
          1. LINQ to SharePoint Examples
        3. LINQ to Services
        4. LINQ for System Engineers
        5. Dynamic LINQ
        6. Other LINQ Enhancements and Tools
        7. Summary
    10. V. Applied LINQ
      1. 18. LINQ in a Multitier Solution
        1. Characteristics of a Multitier Solution
        2. LINQ to SQL in a Two-Tier Solution
        3. LINQ in an n-Tier Solution
          1. Using LINQ to SQL as a DAL Replacement
          2. Abstracting LINQ to SQL with XML External Mapping
          3. Using LINQ to SQL Through Real Abstraction
          4. Using LINQ to XML as the Data Layer
          5. Using LINQ to Entities as the Data Layer
        4. LINQ in the Business Layer
          1. Using LINQ to Objects to Write Better Code
          2. IQueryable<T> vs. IEnumberable<T>
          3. Identifying the Right Unit of Work
          4. Handling Transactions
          5. Concurrency and Thread Safety
        5. Summary
      2. 19. LINQ Data Binding
        1. using LINQ with ASP.NET
          1. Using LinqDataSource
            1. Paging Data with LinqDataSource and DataPager
            2. Handling Data Modifications with LinqDataSource
            3. Using Custom Selections with LinqDataSource
            4. Using LinqDataSource with Custom Types
          2. Using EntityDataSource
            1. Paging Data with EntityDataSource and DataPager
            2. Handling Data Modifications with EntityDataSource
            3. Using Custom Selections with EntityDataSource
          3. Binding to LINQ Queries
        2. using LINQ with WPF
          1. Binding Single Entities and Properties
          2. Binding Collections of Entities
        3. using LINQ with Silverlight
        4. using LINQ with Windows Forms
        5. Summary
    11. Index
    12. About the Authors
    13. Copyright

    Product information

    • Title: Programming Microsoft® LINQ in Microsoft .NET Framework 4
    • Author(s): Paolo Pialorsi and Marco Russo
    • Release date: November 2010
    • Publisher(s): Microsoft Press
    • ISBN: 9780735656765