O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Programming Entity Framework, 2nd Edition

Book Description

Get a thorough introduction to ADO.NET Entity Framework 4 -- Microsoft's core framework for modeling and interacting with data in .NET applications. The second edition of this acclaimed guide provides a hands-on tour of the framework latest version in Visual Studio 2010 and .NET Framework 4. Not only will you learn how to use EF4 in a variety of applications, you'll also gain a deep understanding of its architecture and APIs.

Written by Julia Lerman, the leading independent authority on the framework, Programming Entity Framework covers it all -- from the Entity Data Model and Object Services to WCF Services, MVC Apps, and unit testing. This book highlights important changes for experienced developers familiar with the earlier version.

  • Understand the core concepts you need to make the best use of the EF4 in your applications
  • Learn to query your data, using either LINQ to Entities or Entity SQL
  • Create Windows Forms, WPF, ASP.NET Web Forms, and ASP.NET MVC applications
  • Build and consume WCF Services, WCF Data Services, and WCF RIA Services
  • Use Object Services to work directly with your entity objects
  • Create persistent ignorant entities, repositories, and write unit tests
  • Delve into model customization, relationship management, change tracking, data concurrency, and more
  • Get scores of reusable examples -- written in C# (with notes on Visual Basic syntax) -- that you can implement right away

Table of Contents

  1. Programming Entity Framework
  2. Foreword
  3. Preface
    1. Who This Book Is For
    2. How This Book Is Organized
    3. What You Need to Use This Book
    4. This Book’s Website
    5. Conventions Used in This Book
    6. Using Code Examples
    7. Safari® Books Online
    8. Comments and Questions
    9. Acknowledgments
  4. Author Note for Third Printing, August 2011
    1. Entity Framework 4.1 (Code First and DbContext) Has Released
    2. Entity Framework June 2011 CTP
  5. 1. Introducing the ADO.NET Entity Framework
    1. The Entity Relationship Model: Programming Against a Model, Not the Database
    2. The Entity Data Model: A Client-Side Data Model
    3. Entities: Blueprints for Business Classes
    4. The Backend Database: Your Choice
      1. Database Providers
      2. Access and ODBC
    5. Entity Framework Features: APIs and Tools
      1. Metadata
      2. Entity Data Model Design Tools
        1. Database-first design
        2. Model-first design
        3. Code generation
      3. Object Services
      4. POCO Support
      5. Change Tracking
      6. Relationship Management and Foreign Keys
      7. Data Binding
      8. n-Tier Development
      9. EntityClient
    6. The Entity Framework and WCF Services
    7. What About ADO.NET DataSets and LINQ to SQL?
      1. DataSets
      2. LINQ to SQL
    8. Entity Framework Pain Points Are Fading Away
    9. Programming the Entity Framework
  6. 2. Exploring the Entity Data Model
    1. Why Use an Entity Data Model?
    2. The EDM Within the Entity Framework
    3. Walkthrough: Building Your First EDM
    4. Inspecting the EDM in the Designer Window
      1. Entity Container Properties
      2. Entity Properties
      3. Entity Property Properties
    5. The Model’s Supporting Metadata
    6. Viewing the Model in the Model Browser
    7. Viewing the Model’s Raw XML
    8. CSDL: The Conceptual Schema
      1. EntityContainer
      2. EntitySet
      3. EntityType
        1. The Key element
        2. The Property elements
        3. The navigation properties
      4. Associations
      5. Navigation Property
      6. Navigation Properties That Return Collections
    9. SSDL: The Store Schema
    10. MSL: The Mappings
    11. Database Views in the EDM
    12. Summary
  7. 3. Querying Entity Data Models
    1. Query the Model, Not the Database
    2. Your First EDM Query
      1. Where Did the Context and Classes Come From?
        1. The ObjectContext class, SampleEntities
        2. The entity classes
    3. Querying with LINQ to Entities
      1. Writing Your First LINQ to Entities Query
    4. Querying with Object Services and Entity SQL
      1. Why Another Way to Query?
      2. Entity SQL
        1. Entity SQL canonical functions
      3. The Parameterized ObjectQuery
    5. Querying with Methods
      1. Querying with LINQ Methods
        1. Chaining methods
      2. Querying with Query Builder Methods and Entity SQL
        1. Specifying the control variable
    6. The Shortest Query
    7. ObjectQuery, ObjectSet, and LINQ to Entities
    8. Querying with EntityClient to Return Streamed Data
      1. EntityConnection and the Connection String
      2. EntityCommand
      3. ExecuteReader
      4. Forward-Only Access to the Fields
    9. Translating Entity Queries to Database Queries
      1. Pay Attention to the .NET Method’s Impact on Generated SQL
    10. Avoiding Inadvertent Query Execution
    11. Summary
  8. 4. Exploring LINQ to Entities in Greater Depth
    1. Getting Ready with Some New Lingo
    2. Projections in Queries
    3. Projections in LINQ to Entities
      1. VB and C# Syntax Differences
      2. LINQ Projections and Special Language Features
        1. Anonymous types
        2. Implicitly typed local variables
        3. Implicit and explicit anonymous type creation
      3. Projections with LINQ Query Methods
    4. Using Navigations in Queries
      1. Navigating to an EntityReference
      2. Filtering and Sorting with an EntityReference
      3. Navigating to Entity Collections
      4. Projecting Properties from EntityCollection Entities
        1. Shaped results
        2. Flattened results
      5. Filtering and Sorting with EntityCollections
      6. Aggregates with EntityCollections
        1. Aggregates in LINQ to Entities
      7. Aggregates in LINQ Methods
    5. Joins and Nested Queries
      1. Joins
      2. Nested Queries
        1. Using a nested LINQ query as a projection
        2. Using a nested LINQ query as the collection to be queried
    6. Grouping
      1. Naming Properties When Grouping
      2. Chaining Aggregates
      3. Filtering on Group Conditions
    7. Shaping Data Returned by Queries
      1. Limiting Which Related Data Is Returned
    8. Loading Related Data
      1. Controlling Lazy Loading
        1. Disabling and enabling lazy loading programmatically
        2. Changing the default behavior for lazy loading
      2. Explicitly Loading Entity Collections and Entity References
        1. Loading the EntityReference
        2. Performance considerations with deferred loading
      3. Using the Include Method to Eager-Load
        1. How is the data shaped with Include?
        2. Accessing properties from an Include in the query
      4. Pros and Cons of Load and Include
    9. Retrieving a Single Entity
      1. Retrieving a Single Entity with GetObjectByKey
    10. Finding More Query Samples
    11. Summary
  9. 5. Exploring Entity SQL in Greater Depth
    1. Literals in Entity SQL
      1. Expressing a DateTime Literal
      2. Expressing a Decimal Literal
      3. Using Additional Literal Types
    2. Projecting in Entity SQL
      1. DbDataRecords and Nonscalar Properties
      2. Projecting with Query Builder Methods
    3. Using Navigation in Entity SQL Queries
      1. Navigating to an EntityReference
      2. Filtering and Sorting with an EntityReference
      3. Filtering and Sorting with EntityCollections
      4. Aggregating with EntityCollections
      5. Using Entity SQL SET Operators
      6. Aggregating with Query Builder Methods
    4. Using Joins
    5. Nesting Queries
    6. Grouping in Entity SQL
      1. Returning Entities from an Entity SQL GROUP BY Query
      2. Filtering Based on Group Properties
    7. Shaping Data with Entity SQL
      1. Using Include with an ObjectQuery and Entity SQL
    8. Understanding Entity SQL’s Wrapped and Unwrapped Results
      1. Entity SQL Rules for Wrapped and Unwrapped Results
      2. Digging a Little Deeper into EntityClient’s Results
    9. Summary
  10. 6. Modifying Entities and Saving Changes
    1. Keeping Track of Entities
      1. Managing an Entity’s State
    2. Saving Changes Back to the Database
    3. Inserting New Objects
    4. Inserting New Parents and Children
    5. Deleting Entities
    6. Summary
  11. 7. Using Stored Procedures with the EDM
    1. Updating the Model from a Database
    2. Working with Functions
      1. Function Attributes
    3. Mapping Functions to Entities
      1. Mapping Insert, Update, and Delete Functions to an Entity
        1. Concurrency checking with Use Original Value and Rows Affected Parameter options
      2. Inspecting Mappings in XML
      3. Using Mapped Functions
    4. Using the EDM Designer Model Browser to Import Additional Functions into Your Model
    5. Mapping the First of the Read Stored Procedures: ContactsbyState
      1. Using Imported Functions
      2. Avoiding Inadvertent Client-Side Processing
    6. Mapping a Function to a Scalar Type
    7. Mapping a Function to a Complex Type
    8. Summary
  12. 8. Implementing a More Real-World Model
    1. Introducing the BreakAway Geek Adventures Business Model and Legacy Database
    2. Creating a Separate Project for an EDM
    3. Inspecting and Cleaning Up a New EDM
      1. Modifying the Names of Entities and Properties
      2. Resolving Collisions Between Property Names and Entity Names
      3. Cleaning Up Navigation Property Names
    4. Setting Default Values
    5. Mapping Stored Procedures
      1. Using the Use Original Value Checkbox in Update Mappings
    6. Working with Many-to-Many Relationships
    7. Inspecting the Completed BreakAway Model
    8. Building the BreakAway Model Assembly
      1. Looking at the Compiled Assembly
      2. Splitting Out the Model’s Metadata Files
        1. Moving the schema files
    9. Summary
  13. 9. Data Binding with Windows Forms and WPF Applications
    1. Data Binding with Windows Forms Applications
      1. Creating a Windows Forms Application
      2. Using Windows Forms Data Sources
      3. Creating an Object Data Source for a Customer Entity
      4. Getting an Entity’s Details onto a Form
      5. Adding Code to Query an EDM When a Form Loads
      6. Binding Without a BindingSource
      7. Adding an EntityCollection to the Form
      8. Displaying the Properties of Related Data in the Grid
      9. Allowing Users to Edit Data
      10. Editing Navigation Properties (and Shrinking the Query)
      11. Replacing the Navigation Property TextBoxes with ComboBoxes
      12. Adding New Customers
      13. Deleting Reservations
    2. Data Binding with WPF Applications
      1. Creating the WPF Form
      2. Creating the WPF Project
      3. Adding the Necessary Data Source Objects
      4. Inspecting the XAML and Code Generated by the Automated Data Binding
        1. XAML data-binding elements
      5. Adding Code to Query the EDM When the Window Loads
      6. Customizing the Display of the Controls
      7. Selecting an Entity and Viewing Its Details
      8. Adding Another EntityCollection to the Mix
        1. Working with a many-to-many relationship
        2. Modifying the code to eager-load the related activities
        3. Adding the Activities ListBox and binding it to the Trips ListBox
        4. Testing the application again
      9. Editing Entities and Their Related Data
      10. Using SortDescriptions to Keep Sorting in Sync with Data Modifications
      11. Adding Items to the Child EntityCollection
        1. Testing the new feature for adding activities
      12. The Last Task: Adding New Trips to the Catalog
        1. A few WPF tricks for a more interactive ListBox
        2. Coding the Add New Trip feature
        3. Testing the final version of the WPF demo
    3. Summary
  14. 10. Working with Object Services
    1. Where Does Object Services Fit into the Framework?
    2. Processing Queries
      1. Parsing Queries: From Query to Command Tree to SQL
      2. Understanding Query Builder Methods
        1. Query builder methods and EntitySets
        2. From query builder methods to Entity SQL expressions
        3. Combining LINQ methods and query builder methods
      3. Analyzing a Query with ObjectQuery Methods and Properties
        1. ObjectQuery.ToTraceString
        2. ObjectQuery.CommandText
        3. ObjectQuery.Parameters
        4. ObjectQuery.Context
      4. Executing Queries with ToList, ToArray, First or Single
      5. Executing Queries with the Execute Method
      6. Overriding a Default Connection with ObjectContext.Connection
      7. Handling Command Execution with EntityClient
    3. Materializing Objects
    4. Managing Object State
      1. Using EntityKey to Manage Objects
      2. Merging Results into the Cache with MergeOptions
      3. Inspecting ObjectStateEntry
      4. Maintaining EntityState
    5. Managing Relationships
      1. Attaching and Detaching Objects from the ObjectContext
        1. ObjectContext.AddObject and ObjectSet.AddObject
        2. ObjectContext.Attach and ObjectSet.Attach
        3. ObjectContext.AttachTo
    6. Taking Control of ObjectState
      1. ObjectContext Methods
      2. ObjectStateManager Methods
      3. ObjectStateEntry State Methods for Managing State
      4. ObjectSet State Methods
    7. Sending Changes Back to the Database
      1. ObjectContext.SaveChanges
        1. SaveChanges returns an integer
        2. SaveChanges refreshes the state of tracked entities
      2. Affecting SaveChanges Default Behavior
      3. Overriding SaveChanges Completely
      4. Data Validation with the SavingChanges Event
      5. Concurrency Management
        1. Optimistic concurrency
        2. ConcurrencyMode
        3. OptimisticConcurrencyException
      6. Transaction Support
    8. Implementing Serialization, Data Binding, and More
      1. Object Services Supports XML and Binary Serialization
        1. ObjectContext, ObjectStateManager, and ObjectStateEntry are not serializable
        2. Automatic serialization
          1. XML and DataContract serialization
        3. Binary serialization
        4. Serialization and object state
        5. Explicit serialization
      2. Object Services Supports Data Binding
    9. Summary
  15. 11. Customizing Entities
    1. Partial Classes
    2. Using Partial Methods
      1. The OnContextCreated Method
      2. The On[Property]Changed and On[Property]Changing Methods
      3. Using PropertyChanged to Calculate Database-Computed Columns Locally
    3. Subscribing to Event Handlers
      1. The ObjectContext.ObjectMaterialized Event
      2. The ObjectContext.SavingChanges Event
        1. GetObjectStateEntries: A critical method when validating entities from the context
        2. Implementing SavingChanges
        3. Setting default foreign keys in SavingChanges when no foreign key scalar property exists
      3. The EntityObject.PropertyChanging and EntityObject.PropertyChanged Events
        1. The order of the Changing/Changed events
        2. Event parameters
        3. Subscribing to the class-level PropertyChanging and PropertyChanged events
      4. The AssociationChanged Event
        1. Event arguments
    4. Creating Your Own Partial Methods and Properties
      1. Overriding the Object Constructor
      2. Overriding ObjectContext.SaveChanges
      3. Creating Custom Properties
        1. Using custom properties to perform calculations on child collections
      4. Overloading Entity Creation Methods
      5. Using Partial Classes for More Than Just Overriding Methods and Events
    5. Overriding Default Code Generation
      1. Switching to a Template
      2. Reading the Template
      3. Modifying the Template
        1. Inserting the Managed partial method in each entity class
        2. Other ways to create common methods or properties for all entities
      4. Customizing a Template for Major Class Modifications
      5. Switching Between the Default Template and a Custom Template
    6. Summary
  16. 12. Data Binding with RAD ASP.NET Applications
    1. Using the EntityDataSource Control to Access Flat Data
      1. Creating the Hello Entities Project
      2. Creating a GridView and an EntityDataSource Concurrently
      3. Configuring an EntityDataSource with Its Wizard
      4. Formatting the GridView
      5. Testing the Web Application
    2. Understanding How the EntityDataSource Retrieves and Updates Your Data
      1. EntityDataSource and Its Query
      2. EntityDataSource and Its ObjectContext
        1. Using your own context
      3. EntityDataSource Context Events
      4. EntityDataSource and ViewState
      5. Accessing Foreign Keys When There Is No Foreign Key Property
    3. Working with Related EntityReference Data
      1. Using EntityDataSource.Include to Get Related Data
      2. Displaying Data That Comes from EntityReference Navigation Properties
      3. Using a New EntityDataSource Control to Enable Editing of EntityReference Navigation Properties
      4. Editing EntityReferences That Cannot Be Satisfied with a Drop-Down List
      5. Binding an EntityDataSource to Another Control with WhereParameters
      6. Editing Related Data Concurrently with Multiple EntityDataSource Controls
    4. Working with Hierarchical Data in a Master/Detail Form
      1. Setting Up the Web Application
      2. Specifying Your Own Entity SQL Query Expression for an EntityDataSource
      3. Binding a DropDownList to an EntityDataSource Control
      4. Creating a Parent EntityDataSource That Is Controlled by the DropDownList and Provides Data to a DetailsView
      5. Using the EntityDataSource.Where Property to Filter Query Results
      6. Displaying Read-Only Child Data Through the Parent EntityDataSource
      7. Using a New EntityDataSource to Add a Third Level of Hierarchical Data to the Master/Detail Form
      8. Using the EntityDataSource.Inserting Event to Help with Newly Added Entities
      9. Testing the Application
    5. Exploring EntityDataSource Events
    6. Building Dynamic Data Websites
    7. Summary
  17. 13. Creating and Using POCO Entities
    1. Creating POCO Classes
      1. Creating an ObjectContext Class to Manage the POCOs
        1. Verifying the POCOs with a query
    2. Change Tracking with POCOs
      1. Understanding the Importance of DetectChanges
    3. Loading Related Data with POCOs
      1. Loading from the Context
      2. Lazy Loading from a Dynamic Proxy
    4. Exploring and Correcting POCOs’ Impact on Two-Way Relationships
      1. Using the DetectChanges Method to Fix Relationships
      2. Enabling Classes to Fix Their Own Relationships
    5. Using Proxies to Enable Change Notification, Lazy Loading, and Relationship Fix-Up
      1. Change Notification by Proxy
      2. Lazy Loading by Proxy
      3. Exploring the Proxy Classes
      4. Synchronizing Relationships by Proxy
    6. Using T4 to Generate POCO Classes
      1. Modifying the POCO Template
    7. Creating a Model That Works with Preexisting Classes
    8. Code First: Using Entity Framework with No Model at All
    9. Summary
  18. 14. Customizing Entity Data Models Using the EDM Designer
    1. Mapping Table per Type Inheritance for Tables That Describe Derived Types
      1. Mapping TPT Inheritance
        1. Handling duplicate names and concurrency properties in an inheritance hierarchy
        2. Fixing a potential constraint problem
      2. Querying Inherited Types
      3. POCO Classes and Inherited Objects
      4. Inserting TPT Inherited Types
        1. SaveChanges and newly added derived types
      5. Specifying or Excluding Derived Types in Queries
      6. Creating New Derived Entities When the Base Entity Already Exists
      7. TPT with Abstract Types
    2. Mapping Unique Foreign Keys
    3. Mapping an Entity to More Than One Table
      1. Merging Multiple Entities into One
      2. Querying, Editing, and Saving a Split Entity
      3. Mapping Stored Procedures to Split Tables and More
    4. Splitting a Single Table into Multiple Entities
    5. Filtering Entities with Conditional Mapping
      1. Creating a Conditional Mapping for the Activity Entity
      2. Querying, Inserting, and Saving with Conditional Mappings
      3. Filtering on Other Types of Conditions
      4. Removing the Conditional Mapping from Activity and Re-creating the Category Property
    6. Implementing Table per Hierarchy Inheritance for Tables That Contain Multiple Types
      1. Creating the Resort Derived Type
      2. Setting a Default (Computed) Value on the Table Schema
      3. Testing the TPH Mapping
      4. Choosing to Turn a Base Class into an Abstract Class
    7. Creating Complex Types to Encapsulate Sets of Properties
      1. Defining a Complex Type
      2. Reusing Complex Types
      3. Querying, Creating, and Saving Entities That Contain Complex Types
      4. Removing the Complex Types from the Model
    8. Using Additional Customization Options
      1. Using GUIDs for EntityKeys
      2. Mapping Stored Procedures
      3. Mapping Multiple Entity Sets per Type
      4. Mapping Self-Referencing Associations
    9. Summary
  19. 15. Defining EDM Mappings That Are Not Supported by the Designer
    1. Using Model-Defined Functions
      1. Using Model-Defined Functions to Return More Complex Results
      2. Consuming the Complex Results
      3. Reading the Results from a Complex Function
    2. Mapping Table per Concrete (TPC) Type Inheritance for Tables with Overlapping Fields
    3. Using QueryView to Create Read-Only Entities and Other Specialized Mappings
      1. Finding a Common Use Case for QueryView
      2. Creating a CustomerNameAndID Entity
      3. Creating a QueryView Mapping for CustomerNameAndID
      4. Testing the QueryView
      5. Deconstructing the QueryView
    4. Summary
  20. 16. Gaining Additional Stored Procedure and View Support in the Raw XML
    1. Reviewing Procedures, Views, and UDFs in the EDM
    2. Working with Stored Procedures That Return Data
      1. Using Functions That Match an Entity Whose Property Names Have Been Changed
      2. Query Stored Procedures and Inherited Types
      3. Composing Queries Against Functions
      4. Replacing Stored Procedures with Views for Composability
      5. Queries That Return Multiple Result Sets
    3. Executing Queries on Demand with ExecuteStoreQuery
      1. Querying to a Class That Is Not an Entity
      2. Querying into an Entity
    4. Adding Native Queries to the Model
      1. Defining a Complex Type in the Model Browser
    5. Adding Native Views to the Model
      1. DefiningQuery Is Already in Your Model
      2. Using DefiningQuery to Create Your Own Views
      3. Implementing a DefiningQuery
      4. Creating Associations with the New Entity
        1. Testing the DefiningQuery in an association
      5. Using DefiningQuery to Solve More Complex Problems
    6. Using Commands That Affect the Database
      1. Executing SQL on the Fly with ExecuteStoreCommand
      2. Using Functions to Manipulate Data in the Database
        1. Changing from one derived type to another
    7. Mapping Insert/Update/Delete to Types Within an Inheritance Structure
      1. What If Stored Procedures Affect Multiple Entities in an Inheritance Structure?
    8. Implementing and Querying with User-Defined Functions (UDFs)
    9. Summary
  21. 17. Using EntityObjects in WCF Services
    1. Planning for an Entity Framework–Agnostic Client
      1. Assessing the Pros and Cons of an Entity Framework–Agnostic Consumer
    2. Building a Simple WCF Service with EntityObjects
      1. Creating the Service
      2. Defining the Service Operations
      3. Defining Extra Service Classes
      4. Exposing Custom Properties
    3. Implementing the Service Interface
      1. Adding Graphs to ObjectContext
      2. Deleting Objects
      3. Updating the Object Graph
      4. Client Rules for Identifying Changes in an EntityCollection
      5. The UpdateCustomer Method
      6. Handling New and Existing Reservations
      7. Deleting Reservations
    4. Building a Simple Console App to Consume an EntityObject Service
      1. Enabling the Client Application to Receive Large Messages from the Service
      2. Creating Methods to Test the Service Operations
      3. Analyzing the GetAndUpdateCustomer Method
      4. Testing Out the Other Service Operations
    5. Creating WCF Data Services with Entities
      1. Putting WCF Data Services in Perspective
      2. Creating a WCF Data Service
      3. Filtering at the Service Level Using QueryInterceptor
      4. Anticipating Exceptions
      5. Exposing Related Data Through the Service
      6. Preparing for WCF Data Services’ Limitations
      7. Modifying Data Through a Service
      8. Learning More About Creating and Consuming WCF Data Services
    6. Understanding How WCF RIA Services Relates to the Entity Framework
    7. Summary
  22. 18. Using POCOs and Self-Tracking Entities in WCF Services
    1. Creating WCF-Friendly POCO Classes
      1. Updating the POCO Classes Based on the Current BreakAway Model
      2. Isolating the POCO Entities in Their Own Project
        1. Directing a template back to a model
        2. Specifying the namespace of entity classes
        3. Providing the ObjectContext with a reference to the entities
      3. Adding Custom Logic to the POCO Entities with a Base Class
        1. Modifying the template to apply the inheritance
      4. Following WCF Collection Rules
      5. Preventing Properties from Being Marked As Virtual
    2. Building a WCF Service That Uses POCO Classes
      1. Implementing the Interface
      2. Using the Service
    3. Using the Self-Tracking Entities Template for WCF Services
      1. Creating and Exploring the Self-Tracking Entities
      2. Putting the Change-Tracking Logic Where It’s Needed
      3. Creating a WCF Service That Uses Self-Tracking Entities
      4. Watching Self-Tracking Entities Under the Covers
        1. Debugging the client application
        2. Debugging the SaveCustomer service method
      5. Inspecting the Generated Context Class and Extensions
    4. Using POCO Entities with WCF Data and RIA Services
      1. Preparing for WCF Data Services
        1. Dealing with entities that live in a separate assembly
        2. Avoiding problems caused by dynamic proxies
      2. Using POCO Entities in WCF RIA Services
    5. Sorting Out the Many Options for Creating Services
    6. Summary
  23. 19. Working with Relationships and Associations
    1. Deconstructing Relationships in the Entity Data Model
      1. Understanding How the Entity Data Model Wizard Creates the Association
      2. Understanding Additional Relationship Items
      3. Handling Nonessential Navigation Properties
    2. Understanding the Major Differences Between Foreign Key Associations and Independent Associations
      1. Defining Associations in Metadata
      2. Detecting Associations at Runtime
    3. Deconstructing Relationships Between Instantiated Entities
      1. Understanding Relationship Manager and the IRelatedEnd Interface
      2. Late-Binding Relationships
      3. Taking a Peek Under the Covers: How Entity Framework Manages Relationships
      4. Understanding Navigation Properties
        1. EntityReference properties
          1. EntityReference.Value
          2. What if there is no EntityReference
        2. EntityCollection properties
      5. Understanding Referential Integrity and Constraints
        1. Constraints that are not checked until they hit the database
        2. Checking for missing entity references with and without foreign keys
      6. Implementing Deletes and Cascading Deletes
        1. Cascading deletes in the database
        2. Recommendation: Cascade in both the model and the database, or in neither
    4. Defining Relationships Between Entities
      1. The CLR Way: Setting a Navigation Property to an Entity
      2. Setting a Foreign Key Property
      3. Setting an EntityReference Using an EntityKey
      4. Loading, Adding, and Attaching Navigation Properties
      5. Lazy Loading
      6. EntityReference.Load and EntityCollection.Load
      7. Loading from Detached Entities: Lazy and Explicit
      8. Using EntityCollection.Add
        1. Adding new entities that are detached
        2. Adding existing entities that are detached
        3. Adding new or existing entities that are attached
        4. Adding entities to the EntityCollection of a detached object
      9. Using Attach and Remove
      10. Moving an Entity to a New Graph
    5. Learning a Few Last Tricks to Make You a Relationship Pro
      1. Using CreateSourceQuery to Enhance Deferred Loading
      2. Getting a Foreign Key Value in an Independent Association
    6. Summary
  24. 20. Real World Apps: Connections, Transactions, Performance, and More
    1. Entity Framework and Connections
      1. Overriding EntityConnection Defaults
      2. Working with Connection Strings Programmatically
        1. Constructing connection strings on the fly with the EntityConnectionStringBuilder class
          1. Choosing and loading a model programmatically
      3. Opening and Closing Connections
        1. Understanding the default connection usage
          1. Default behavior 1: Many calls on a single connection
          2. Default behavior 2: Multiple connections
        2. Forcing an explicit connection
      4. Getting the Store Connection from EntityConnection
      5. Disposing Connections
      6. Pooling Connections
    2. Fine-Tuning Transactions
      1. Why Use Your Own Transaction?
      2. Understanding Implicit Entity Framework Transactions
        1. Understanding SaveOptions and AcceptAllChanges in a transaction
      3. Specifying Your Own Read/Write Transactions
      4. Specifying Your Own Read-Only Transactions
      5. Rolling Back Transactions
    3. Understanding Security
      1. Guarding Against SQL Injection
        1. Taking precautions with dynamic queries
        2. Entity SQL injection
      2. Guarding Against Connection Piggybacks
    4. Fine-Tuning Performance
      1. Measuring Query Performance
      2. Measuring Startup Performance
      3. Reducing the Cost of Query Compilation
      4. Caching for Entity SQL Queries
        1. Comparing EntityClient to Object Services
      5. Precompiling Views for Performance
        1. Pregenerating views for performance
        2. Pregenerating views into an existing project
      6. Precompiling LINQ to Entities Queries for Performance
      7. Fine-Tuning Updates for Performance?
      8. Lacking Support for Full Text Searches
    5. Exploiting Multithreaded Applications
      1. Forcing an ObjectContext to Use Its Own Thread
      2. Implementing Concurrent Thread Processing
    6. Exploiting .NET 4 Parallel Computing
    7. Summary
  25. 21. Manipulating Entities with ObjectStateManager and MetadataWorkspace
    1. Manipulating Entities and Their State with ObjectStateManager
      1. Refreshing Your High-Level Understanding of ObjectStateEntry
      2. Getting an ObjectStateManager and Its Entries
        1. Getting groups of entries with GetObjectStateEntries
      3. Building Extension Methods to Overload GetObjectStateEntries
      4. Building a Method to Return Managed Entities
      5. Using GetObjectStateEntry and TryGetObjectStateEntry
      6. Mining Entity Details from ObjectStateEntry
        1. Reading and writing values
        2. Accessing object metadata with CurrentValueRecord.DataRecordInfo
        3. Getting started with the FieldMetadata hierarchy
      7. Leveraging the ObjectStateManager During Saves
    2. Using ObjectStateManager to Build an EntityState Visualizer
      1. Retrieving an ObjectStateEntry Using an EntityKey
      2. Reading the OriginalValues and CurrentValues of an ObjectStateEntry
      3. Determining Whether a Property Has Been Modified
      4. Displaying the State and Entity Type
      5. Getting ComplexType Properties Out of ObjectStateEntry
      6. Modifying Values with ObjectStateManager
      7. Working with Relationships in ObjectStateManager
        1. Building graphs directly with the RelationshipManager
    3. Using the MetadataWorkspace
      1. Loading the MetadataWorkspace
        1. Creating a MetadataWorkspace without an EntityConnection
      2. Clearing the MetadataWorkspace from Memory
      3. Understanding the MetadataWorkspace ItemCollections
        1. Determining whether an ItemCollection has been loaded
      4. Retrieving Metadata from the MetadataWorkspace
        1. Retrieving sets of items from the metadata with GetItems and TryGetItem
        2. Retrieving specific items from the metadata with GetItem and TryGetItem
        3. Retrieving functions from the metadata with GetFunctions and TryGetFunctions
      5. Querying the Metadata with LINQ to Objects
    4. Building Dynamic Queries and Reading Results
      1. Building Entity SQL Queries Dynamically Using Metadata
      2. Creating Queries on the Fly with CreateObjectSet and Query Builder Methods
        1. Leveraging CreateObjectSet to return Entity SQL, not just a query
      3. Reading the Results of a Dynamically Created Query
    5. Creating and Manipulating Entities Dynamically
      1. Creating EntityObjects Without Entity Classes
        1. Creating a new entity with CreateInstance
          1. Getting a reference to an assembly
          2. Creating an entity from the assembly
        2. Using System.Type to inspect the EntityType
      2. Creating Entities and Graphs Dynamically
        1. Custom extension methods used by AddChildToParentObject
        2. Calling the AddChildToParentObject method
    6. Summary
  26. 22. Handling Exceptions
    1. Preparing for Exceptions
    2. Handling EntityConnectionString Exceptions
      1. Connection String Can’t Be Found or Is Improperly Configured: System.ArgumentException
      2. Metadata Files Cannot Be Found: System.Data.MetadataException
      3. Handling Connection String Exceptions
    3. Handling Query Compilation Exceptions
      1. Invalid LINQ to Entities Query Expressions: System.NotSupportedException
      2. Invalid Entity SQL Query Expressions: EntitySqlException
        1. Handling an EntitySqlException
      3. EntityCommandCompilationException Thrown by the Store Provider
    4. Creating a Common Wrapper to Handle Query Execution Exceptions
    5. Handling Exceptions Thrown During SaveChanges Command Execution
      1. UpdateException: Thrown When Independent Association Mapping Constraints Are Broken
      2. UpdateException: Thrown by Broken Constraints in the Database
      3. Relying on Entity Framework to Automatically Roll Back When an UpdateException Occurs
      4. Gleaning Details from UpdateException
      5. Planning for Other Exceptions Related to the Entity Framework
    6. Handling Concurrency Exceptions
    7. Summary
  27. 23. Planning for Concurrency Problems
    1. Understanding Database Concurrency Conflicts
    2. Understanding Optimistic Concurrency Options in the Entity Framework
      1. Ignoring Concurrency Conflicts
      2. Forcing the User’s Data to the Server (ClientWins)
      3. Refreshing the User’s Data with Server Data (StoreWins)
      4. Determining the Scope of Changes
      5. Using rowversion (a.k.a. timestamp) for Concurrency Checks
    3. Implementing Optimistic Concurrency with the Entity Framework
      1. Flagging a Property for Concurrency Checking
      2. How the Entity Framework Uses the ConcurrencyMode Property
      3. Concurrency Checking Without a rowversion Field
      4. Concurrency Checking on a Checksum in the Data Store
      5. Concurrency Checks for EntityReference Navigation Properties
      6. Concurrency Checks and Inherited Types
      7. Concurrency Checks and Stored Procedures
        1. Defining a stored procedure to perform concurrency checking
    4. Handling OptimisticConcurrencyExceptions
      1. Using ObjectContext.Refresh
      2. Using Refresh with ClientWins
      3. Using Refresh with StoreWins
      4. Refreshing Collections of Entities
      5. Refreshing Related Entities in a Graph
      6. Rewinding and Starting Again, and Maybe Again After That
      7. Reporting an Exception
    5. Handling Concurrency Exceptions at a Lower Level
      1. Handling Exceptions in a Granular Way Without User Intervention
      2. Handling Multiple Conflicts
        1. Separating the good from the bad and the ugly
    6. Handling Exceptions When Transactions Are Your Own
    7. Summary
  28. 24. Building Persistent Ignorant, Testable Applications
    1. Testing the BreakAway Application Components
    2. Getting Started with Testing
      1. Writing an Integration Test That Hits the Database
      2. Inspecting a Failed Test
      3. Writing a Unit Test That Focuses on Custom Logic
    3. Creating Persistent Ignorant Entities
      1. Planning the Project Structure
      2. Starting with the Model and Its POCO Entities
      3. Building an Interface to Represent a Context
      4. Modifying the BAEntities ObjectContext Class to Implement the New Interface
        1. Disconnecting the context class from the T4 template
        2. Implementing the IContext interface
        3. Implementing the remaining interface members
      5. Creating the IEntityRepository Interface
      6. Creating the Repository Classes
      7. Testing GetReservationsForCustomer Against the Database
      8. Creating a Fake Context
      9. Creating a FakeObjectSet Class
      10. Completing the Fake Context
        1. Modify the tests to use the fake repository
        2. Rerun the tests
    4. Building Tests That Do Not Hit the Database
      1. Adding Validation Logic to the POCO Class
      2. Adding Validation Logic to the Context
      3. Providing ManagedEntities in the FakeContext
      4. Hiding the Context from the Lower Layers with Unit of Work
      5. Testing UnitOfWork Against the Database
      6. Enabling Eager Loading in IContext
        1. Eager loading with a fake context
      7. Leveraging Precompiled Queries in Your Repositories
    5. Using the New Infrastructure in Your Application
      1. Adding a UI Layer That Calls the Repository
    6. Application Architecture Benefits from Designing Testable Code
    7. Considering Mocking Frameworks?
    8. Summary
  29. 25. Domain-Centric Modeling
    1. Creating a Model and Database Using Model First
      1. Creating a Conceptual Model in the Designer
      2. Creating the Entities
        1. Setting attributes of the entity’s properties
      3. Creating Association and Inheritance Hierarchies
        1. Creating a one-to-many relationship
        2. Creating a many-to-many relationship
        3. Creating an inheritance hierarchy
      4. Generating Database Schema from the Model
        1. Exploring the generated DDL
        2. Looking at the result of the inheritance
        3. Noting the result of the many-to-many relationship
        4. Exploring the constraints
        5. Completing the generation of the DDL
      5. Creating the Database and Its Schema
      6. Overriding the DDL Generation
    2. Using the Feature CTP Code-First Add-On
      1. Understanding Code-First Design
      2. Installing the Feature CTP
      3. Exploring Some Configuration Examples
      4. Testing the Code-First Application and Database
    3. Using SQL Server Modeling’s “M” Language
      1. Using M Metadata in Entity Framework Applications
    4. Summary
  30. 26. Using Entities in Layered Client-Side Applications
    1. Isolating the ObjectContext
      1. Freeing Entities from Change Tracking
      2. Enabling Change Tracking Across Tiers
      3. Moving Other ObjectContext-Dependent Logic to the DataBridge
      4. Ensuring That Lazy Loading Doesn’t Negatively Impact the Layered Application
      5. Noting Additional Benefits of the Layered Application
    2. Separating Entity-Specific Logic from ObjectContext Logic
    3. Working with POCO Entities
      1. Providing EntityState
      2. Providing Logic in Place of Other EntityObject Behavior
    4. Summary
  31. 27. Building Layered Web Applications
    1. Understanding How ObjectContext Fits into the Web Page Life Cycle
      1. Return Results, Not Queries, from the DataBridge Class
      2. Using Entities in Read-Only Web Pages
      3. Exploring Options for Updating Entities in an ASP.NET Web Forms Application
        1. Single or batch updates?
        2. Persist entities or use independent values?
      4. Comparing ASP.NET’s State Solutions to the Needs of the Entity Framework
        1. View state
        2. Application cache and session state
    2. Building an N-Tier Web Forms Application
      1. Designing the Application
      2. Using the Existing Repositories
      3. Building an Entity Manager to Act As a DataBridge
      4. Retrieving Data for Display and for Future Updates
      5. Making the Related Data Accessible to the Client
      6. Getting Data from the Manager to the Client
      7. Adding Lists for User Selection Controls
      8. Allowing a User to Modify Related Data
    3. Building an ASP.NET MVC Application
      1. Replacing the Context with Repositories
    4. Editing Entities and Graphs on an MVC Application
      1. Creating a Repository for Payments
      2. Interacting with the ReservationController
    5. Summary
  32. A. Entity Framework Assemblies and Namespaces
    1. Unpacking the Entity Framework Files
    2. Exploring the Namespaces
      1. Existing Namespaces That Include Entity Framework Classes and Functionality
      2. Entity Framework-Specific Namespaces
  33. B. Data-Binding with Complex Types
    1. Using Complex Types with ASP.NET EntityDataSource
    2. Identifying Unexpected Behavior When Binding Complex Types
      1. Successfully Using Binding to Complex Types in ASP.NET Without Data Source Controls
        1. List controls
        2. Data-bound controls
        3. Templated controls
      2. Windows Forms DataSource and Complex Types
  34. C. Additional Details About Entity Data Model Metadata
    1. Seeing EDMX Schema Validation in Action
    2. Additional Conceptual Model Details
      1. Schema
      2. XML Representation of an Association
      3. AssociationSet
    3. Additional SSDL Metadata Details
      1. SSDL Association and AssociationSet Elements
        1. ReferentialConstraint
    4. Additional MSL Metadata Details
      1. The MSL Elements
        1. Mapping
        2. EntityContainerMapping
        3. EntitySetMapping
          1. EntityTypeMapping
          2. MappingFragment
          3. ScalarProperty
        4. AssociationSetMapping
  35. Index
  36. About the Author
  37. Colophon
  38. Copyright