You are previewing Programming Entity Framework.
O'Reilly logo
Programming Entity Framework

Book Description

Programming Entity Framework is a thorough introduction to Microsoft's core framework for modeling and interacting with data in .NET applications. This highly-acclaimed book not only gives experienced developers a hands-on tour of the ADO.NET Entity Framework (EF) and explains its use in a variety of applications, it also provides a deep understanding of its architecture and APIs. Although this book is based on the first version of Entity Framework, it will continue to be extremely valuable as you shift to the Entity Framework version in .NET Framework 4.0 and Visual Studio 2010. From the Entity Data Model (EDM) and Object Services to EntityClient and the Metadata Workspace, Programming Entity Framework covers it all. Author Julia Lerman, the leading independent authority on the framework, includes scores of reusable examples -- written in both Visual Basic and C# -- that you can implement right away. This book will help you :

  • Understand the core concepts you need to make the best use of the Entity Framework (EF) in your applications

  • Learn to query your data, using either LINQ to Entities or Entity SQL

  • Create Windows Forms, WPF, and ASP.NET applications

  • Build ASMX web services and WCF services

  • Use Object Services to work directly with your entity objects

  • Delve into model customization, relationship management, change tracking, data concurrency, and more

Presented in a clear narrative style that reflects the hundreds of hours the author has spent consulting, teaching, and writing about this new data access technology and testing its myriad features, Programming Entity Framework will help you master the technology and put it to work.

Table of Contents

  1. Programming Entity Framework
  2. A Note Regarding Supplemental Files
  3. Foreword
  4. 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
  5. 1. Introducing the ADO.NET Entity Framework
    1. Programming Against a Model, Not Against the Database
    2. The Entity Data Model: A Client-Side Data Model
    3. The Entity in “Entity Framework”
    4. Choosing Your Backend
      1. Available Providers
      2. Access and ODBC
    5. Entity Framework Features
      1. The Entity Data Model
      2. Entity Data Model Design Tools
        1. The Entity Data Model Wizard
      3. Managing Objects with Object Services
      4. Change Tracking
      5. Relationship Management
      6. Data Binding
      7. EntityClient
    6. The Entity Framework in Web Services
    7. What About ADO.NET DataSets and LINQ to SQL?
      1. DataSets
      2. LINQ to SQL
    8. Entity Framework Pain Points
      1. The Entity Framework Designer
        1. Stored procedures
        2. Unsupported EDM types
        3. Generating a database from the model
        4. A host of little things
      2. Challenges with Change Tracking Distributed Applications
      3. Domain-Driven Development
      4. Unit Testing
    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. Your First EDM
    4. The EDM in the Designer Window
    5. Entity Properties
      1. Editing the Entity Set and Navigation Property Names
    6. The Naked Model: Inspecting the Model’s XML
    7. A Less Daunting Model View
    8. The Three Parts of the Model
    9. CSDL: The Conceptual Schema
      1. Schema
      2. EntityContainer
      3. EntitySet
      4. EntityType
        1. The Key element
        2. The Property elements
        3. The navigation properties
      5. Associations
      6. AssociationSet
      7. NavigationProperty
      8. Navigation Properties That Return Collections
      9. Where Are the Foreign Keys?
    10. SSDL: The Store Schema
      1. Association and AssociationSet
        1. ReferentialConstraint
    11. MSL: The Mappings
      1. The MSL Elements
        1. Mapping
        2. EntityContainerMapping
        3. EntitySetMapping
          1. EntityTypeMapping
          2. MappingFragment
          3. ScalarProperty
        4. AssociationSetMapping
    12. Database Views in the EDM
    13. Code Generation from EDM to Classes
    14. Summary
  7. 3. Querying Entity Data Models
    1. Query the Model, Not the Database
    2. Your First EDM Query
      1. A More Query-Like Query
      2. Where Did the Context and Classes Come from?
        1. The ObjectContext class, ProgrammingEFDB1Entities
        2. The entity classes
    3. LINQ to Entities Queries
      1. ObjectQuery and LINQ to Entities
    4. Entity SQL Queries That Return Objects
      1. Why Another Way to Query?
      2. Entity SQL
        1. Entity SQL canonical functions
      3. The Parameterized ObjectQuery
    5. Method-Based Syntax Queries for LINQ and Entity SQL
      1. LINQ Method-Based Queries
        1. Chaining methods
      2. ObjectQuery’s Query Builder Methods
        1. Specifying the control variable
    6. The Shortest Query
    7. EntityClient: The Lowest-Level Method for Returning Streamed Data Through EDM Queries
      1. EntityConnection and the Connection String
      2. EntityCommand
      3. ExecuteReader
      4. Forward-Only Access to the Fields
    8. Translation to Database Queries
      1. Pay Attention to the .NET Method’s Impact on Generated SQL
    9. Avoid Inadvertent Query Execution
    10. Summary
  8. 4. Exploring EDM Queries in Greater Depth
    1. Same Model, Friendlier Name
    2. Projections in Queries
      1. Projections in LINQ to Entities
        1. VB and C# syntax differences
      2. LINQ Projections and New Language Features
        1. Anonymous types
        2. Implicitly typed local variables
        3. Implicit and explicit anonymous type creation
      3. Projections with LINQ Query Methods
    3. Projections in Entity SQL
      1. DbDataRecords and Nonscalar Properties
      2. Projecting with Query Builder Methods
    4. Querying Across Associations
      1. Navigation 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
        2. Aggregates in Entity SQL
      7. Entity SQL SET Operators
      8. Aggregates in LINQ Methods and Query Builder 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
        3. Nested queries in Entity SQL
    6. Grouping
      1. Naming Properties When Grouping
      2. Chaining Aggregates
      3. Filtering on Group Conditions
      4. Grouping in Entity SQL
        1. Returning entities from an Entity SQL GROUP BY query
        2. Filtering based on group properties
    7. Shaped Data Returned by Queries
      1. Shaped Data from Entity SQL
    8. Deferred Loading and Eager Loading Queries
      1. Deferred Loading Entity Collections with Load
        1. Performance considerations with deferred loading
        2. Loading the EntityReference
      2. Using the Include Method to Eager-Load
        1. How is the data shaped with Include?
        2. Accessing properties from an Include in the query
      3. Using Include with an ObjectQuery
      4. Pros and Cons of Load and Include
    9. Retrieving a Single Entity
    10. Retrieving a Single Entity with GetObjectByKey
    11. 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
    12. Summary
  9. 5. Modifying Entities and Saving Changes
    1. How ObjectContext Manages Entities
      1. Remembering Original Values and Keeping Track of Changes
    2. The SaveChanges Method
      1. From Entity Framework Command to Native Command
    3. Adding New Entities
      1. Breaking Down the Native Insert Command
    4. Inserting New Parents and Children
    5. Deleting Entities
    6. Summary
  10. 6. Using Stored Procedures with the EDM
    1. Adding the Stored Procedures into the Model
    2. Working with Functions
      1. Function Attributes
    3. Implementing Functions
      1. Rules for Mapping Functions to Entities
      2. Wiring Up Insert, Update, and Delete Functions to an Entity
        1. The Use Original Value option
      3. Inspecting the Mappings in the XML
      4. Using These Mapped Functions
        1. What about the read stored procedure?
    4. The EDM Designer’s Model Browser
    5. Mapping the Last of the Four Functions: CustomersbyState
      1. Using the CustomersbyState Function
      2. Using Functions in a Query
    6. More About the Update Model Wizard
      1. A Frequently Asked Question About Deleting Entities from the Model
    7. Summary
  11. 7. Tuning Up a Model
    1. The BreakAway Geek Adventures Business Model
    2. Creating a Class Library Project to Host an EDM
    3. Inspecting and Cleaning Up a New Model
      1. Modifying the Names of Entities
      2. Collisions Between Property Names and Entity Names
    4. Cleaning Up Navigation Property Names
      1. Entities with Multiple Relationships to a Single Entity
      2. Determining Which Navigation Property Is Mapped to Which Foreign Key Field
    5. Mapping a Few Stored Procedures
      1. Mapping the Insert Function
      2. Mapping the Update Function
        1. Using the Use Original Value checkbox
        2. The DeleteFunction mapping and an awkward stored procedure parameter
    6. Working with Many-to-Many Relationships
    7. Building the BreakAwayModel Project
      1. Don’t Overlook the Assembly and Model Names
        1. BAGA assembly namespace
        2. Entity container name
        3. Model namespace
      2. The Impact of Compiling a Project on an EDMX File
        1. Splitting out the schema files
        2. Moving the schema files
    8. Summary
  12. 8. 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 to Help with Data Binding
      3. Creating an Object Data Source for a Customer Entity
      4. Getting the Entity’s Details onto the Form
      5. Adding Code to Perform the EDM Query
      6. Testing the Sample
      7. Entities, BindingSources, and a Very Important Rule
      8. Adding the Related EntityCollection to the Form
        1. Displaying the properties of reference properties in the grid
        2. Testing the new version of the sample
      9. Allowing the User to Edit the Data
        1. Enabling the Save button
        2. Changing the scope of the ObjectContext
        3. Adding the save logic to the Save button
        4. Test editing a customer
      10. Editing the Navigation Properties (and Trimming Down the Query)
        1. Reorganizing data retrieval
        2. Replacing the navigation property TextBoxes with ComboBoxes
        3. Testing the sample again
      11. Adding New Customers
        1. From toolbar to BindingSource to context
        2. Adding the code to ensure that new customers are created properly
        3. Testing the form’s add functionality
    2. Data Binding with WPF Applications
      1. Creating the WPF Form
      2. Creating the New Project
      3. Adding Code to Query the Entities That Drive the Form
      4. XAML’s Role in Data Binding
      5. Binding with the ListBox
      6. Testing the Example
      7. Selecting an Entity and Seeing Its Details
        1. Binding the TextBox controls to the ListBox
        2. Binding the ComboBox controls to the ListBox and to the data
        3. Testing the sample
      8. Adding Another EntityCollection to the Mix: Activities
        1. The *:* relationship between trips and activities
        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 Trip Entities and Their Related Data
        1. What if the user changes the destination?
      10. Adding Items to the Child EntityCollection
        1. Testing the new feature for adding activities
      11. 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. Validating the new trip before saving
        4. Testing the final version of the WPF demo
    3. Summary
  13. 9. Working with Object Services
    1. Where Does Object Services Fit into the Framework?
    2. Query Processing
      1. From Query to Command Tree to SQL
        1. From a LINQ to Entities query to a command tree
        2. From Entity SQL and query builder methods to a command tree
        3. How EntityClient turns command trees into store commands
      2. A Better Understanding of 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. Breaking Apart the ObjectQuery
        1. ToTraceString
        2. ObjectQuery.CommandText
        3. ObjectQuery.Parameters
        4. ObjectQuery.Context
      4. Query Execution with the ToList or ToArray Method
      5. Query Execution with the Execute Method
      6. ObjectContext.Connection
        1. Why does the context need the EntityConnection?
      7. Handling Command Execution with EntityClient
    3. Object Materialization
    4. The ObjectContext
      1. ObjectContext Is a Cache for In-Memory Objects
        1. Objects are not required to be in the ObjectContext cache
      2. Entity Objects
      3. EntityKey and EntityState
        1. The EntityState enums
      4. Merging Results into the Cache
    5. State Management and ObjectStateEntry
      1. Change Tracking
    6. Relationship Management
      1. Attaching and Detaching Objects from the ObjectContext
        1. ObjectContext.Add
        2. ObjectContext.Attach
        3. ObjectContext.AttachTo
        4. Creating an EntityKey on the fly
      2. ObjectContext.ApplyPropertyChanges: A Handy Method for Updating Entities
    7. Sending Changes Back to the Database
      1. ObjectContext.SaveChanges
      2. SaveChanges Returns an Integer
      3. Data Validation with the SavingChanges Event
      4. Concurrency Management
        1. Optimistic concurrency
        2. ConcurrencyMode
        3. OptimisticConcurrencyException
      5. Transaction Support
    8. Additional Features
      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
      3. Object Services Supports Custom Classes
        1. IEntityWithChangeTracker
        2. IEntityWithKey
        3. IEntityWithRelationships
    9. Summary
  14. 10. Customizing Entities
    1. Partial Classes
    2. Customizable Methods
      1. The OnContextCreated Method
        1. Implementing OnContextCreated
      2. The On[Property]Changed and On[Property]Changing Methods
        1. Implementing the property-level PropertyChanged and PropertyChanging methods
      3. Using PropertyChanged to Calculate Database-Computed Columns Locally
    3. Customizable Event Handlers
      1. The ObjectContext.SavingChanges Event
        1. Implementing SavingChanges
      2. The EntityObject.PropertyChanging and EntityObject.PropertyChanged Events
        1. The order of the Changing/Changed events
        2. Event parameters
        3. Implementing the class-level PropertyChanging and PropertyChanged events
      3. The AssociationChanged Event
        1. Event arguments
    4. Other Opportunities for Customization
      1. Custom Properties
      2. Custom Properties That Perform Calculations on Child Collections
      3. Overloading Context and Entity Methods
      4. Partial Classes Are for More Than Just Overriding Existing Methods and Events
      5. Custom Code Generation
      6. Creating Common Methods or Properties for All Entities
    5. Summary
  15. 11. Using the ASP.NET EntityDataSource Control
    1. Getting to First Base with the EntityDataSource Control and Flat Data
      1. Creating the Hello Entities Project
      2. Creating a GridView and an EntityDataSource Concurrently
      3. Configuring an EntityDataSource Through Its Wizard
      4. Formatting the GridView
      5. Testing the Web Application
    2. Understanding How the EntityDataSource Is Able to Retrieve and Update Your Data
      1. EntityDataSource and Its Query
        1. Other EntityDataSource properties that impact the query
      2. EntityDataSource and Its ObjectContext
        1. Using your own context
      3. EntityDataSource Context Events
      4. EntityDataSource and ViewState
    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
        1. Coding the EntityDataSource’s Selected event to populate a control with navigation property details
      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. Browsing Through the EntityDataSource Events
      1. EntityDataSource Events and Page Events
    6. Summary
  16. 12. Customizing Entity Data Models
    1. Designer Support for Mappings
    2. Mapping Table per Type Inheritance for Tables That Describe Derived Types
      1. Mapping TPT Inheritance
      2. Fixing the Impact of the New Inheritance on the Customer’s Associations with Other Entities
      3. Handling Properties with the Same Name
      4. Querying Inherited Types
      5. Creating a Project to Test the New Mappings
      6. Testing the TPT Inheritance
      7. SaveChanges and Newly Added Derived Types
      8. Specifying or Excluding Derived Types in Queries
      9. Creating New Derived Entities When the Base Entity Already Exists
      10. TPT with Abstract Types
    3. Using Entity Splitting to Map a Single Entity to More Than One Table
      1. Merging Multiple Entities into One
      2. Testing Entity Splitting
    4. Using Conditional Mapping to Filter Entity Mappings
      1. Creating a Conditional Mapping for the Activity Entity
        1. The Is Null/Not Null conditions
      2. Testing the Conditional Mapping
        1. Filtering on other types of conditions
        2. Removing the conditional mapping from Activity and re-creating the Category property
    5. Implementing Table per Hierarchy Inheritance for Tables That Contain Multiple Types
      1. Creating the Resort Derived Type
      2. Setting a Default Value on the Table Schema
      3. Testing the TPH Mapping
      4. Abstract Entity Types
      5. Which of These Mappings Is Better?
    6. Implementing Customizations That Are Not Supported by the EDM Designer
    7. Mapping Table per Concrete (TPC) Type Inheritance for Tables with Overlapping Fields
    8. Creating Complex Types to Encapsulate Sets of Properties
      1. Complex Types and the EDM Designer
      2. Defining a Complex Type
      3. Replacing Properties with a Complex Type
      4. Mapping Entities with Complex Types
      5. Complex Types Are Not EntityObjects
      6. Using Complex Types
      7. Complex Types in Data-Binding Scenarios
        1. ASP.NET EntityDataSource
      8. Data Binding Complex Types in ASP.NET Without the EntityDataSource
        1. Complex types with ASP.NET binding controls
          1. List controls
          2. Data-bound controls
          3. Templated controls
      9. Windows Forms DataSource and Complex Types
      10. Removing the Complex Types from the Model
    9. Using QueryView to Create Read-Only Entities and Other Specialized Mappings
      1. Creating a Simple QueryView
      2. Testing the QueryView
      3. Deconstructing the QueryView
      4. QueryView with Inherited Types
        1. When will the Entity Framework use the QueryView for the derived type?
        2. The default QueryView needs to account for derived types
      5. Testing the New QueryView
    10. Additional Customization Options
      1. Mapping Stored Procedures
      2. Multiple Entity Sets per Type
      3. Self-Referencing Associations
    11. Summary
  17. 13. Working with Stored Procedures When Function Mapping Won’t Do
    1. Does the Procedure Line Up with an Entity?
    2. Overview of Procedures, UDFs, and TVFs in the EDM
    3. Composing Queries Against Functions
    4. Mapping and Executing Query Stored Procedures
      1. Using Functions That Match an Entity Whose Property Names Have Been Changed
        1. How can you get around this problem?
      2. Query Stored Procedures and Inherited Types
      3. Queries That Return Randomly Shaped Results
      4. Replacing Stored Procedures with Views
      5. Queries That Return Multiple Resultsets
      6. Queries That Return Primitive Types
    5. Adding Native Queries to the Model
    6. 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
        1. Creating an association from the new entity
        2. Testing the DefiningQuery
      4. Using DefiningQuery to Solve More Complex Problems
    7. Using Commands That Affect the Persisted Database
      1. DML Functions That Return Entities
      2. Insert, Update, and Delete Functions That Don’t Return an Entity
        1. Returning a scalar value
        2. Returning nothing
    8. Defining Insert, Update, and Delete Stored Procedures Directly in the Model
      1. What Do the Functions Look Like?
    9. Mapping Insert/Update/Delete to Types Within an Inheritance Structure
      1. What If Stored Procedures Affect Multiple Entities in an Inheritance Structure?
    10. Implementing and Querying with User-Defined Functions (UDFs)
    11. Summary
  18. 14. Using Entities with Web and WCF Services
    1. Building a Client That Is Ignorant of the Entity Framework
      1. Pros and Cons of an Entity Framework-Agnostic Consumer
    2. Using the Entity Framework with ASMX Web Services
      1. Building the ASMX Service
        1. Creating the web service
        2. The GetCustomers method
        3. Testing the GetCustomers service operation
        4. Adding a method to return a single customer
        5. Testing the new method
        6. What about interoperability?
        7. The insert and update web methods
        8. The path of least resistance
      2. Building the Client Application
        1. Setting up the client project and the proxy to the service
        2. Adding methods to interact with the web service
        3. Designing the form
        4. Adding the New and Save buttons
        5. Testing your application
        6. The client-side Customer versus the server-side Customer
    3. Using the Entity Framework with WCF Services
      1. Building the WCF Service
        1. Creating the service application
        2. Defining the operations the service will provide
        3. Defining the DataContract classes the service will use
        4. Enabling the model’s partial class properties for Trip and Reservation to participate in the service
        5. Implementing the service interface
        6. Adding graphs to ObjectContext
        7. Deleting objects
        8. Updating the ObjectGraph
        9. Client rules for identifying changes in an EntityCollection
        10. The UpdateCustomer method
        11. Why call ApplyPropertyChanges if there were no changes?
        12. Handling existing reservations
        13. Dealing with new reservations
        14. Deleting reservations
        15. Wrapping up the UpdateCustomer method with SaveChanges
      2. Building the Client to Consume the WCF Service
        1. Editing the configuration for the web service client
        2. Testing the form again
        3. Adding functionality to view the reservations
        4. Testing the form so far
        5. Finishing the form
        6. Adding and deleting the reservations
        7. Running the application and saving your changes
        8. Peeking under the covers
    4. Summary
  19. 15. Working with Relationships and Associations
    1. Deconstructing Relationships in the Entity Data Model
      1. How Did the Entity Data Model Wizard Create the Association?
      2. Additional Items Created in the Model
      3. Navigation Properties Are Not Required
      4. Understanding How Associations Impact the Native Query
    2. Deconstructing Relationships Between Instantiated EntityObjects
      1. Relationships Are First-Class Citizens
      2. The “Platinum Rule” About Related Entities That Are Attached or Detached from the ObjectContext
      3. The Relationship Manager and the IRelatedEnd Interface
        1. The Relationship Manager provides related objects through late binding
      4. Experimenting with Relationship Span
      5. Understanding Navigation Properties in Entity Objects
        1. EntityReference properties
          1. EntityReference.Value
          2. What if there is no EntityReference
        2. EntityCollection properties
      6. Referential Integrity and Constraints
        1. Constraints that are not checked until they hit the database
        2. Constraints that the Entity Framework checks when SaveChanges is called
      7. Deletes and Cascading Deletes
        1. Cascading deletes in the database
        2. Cascading deletes in the EDM
        3. Recommendation: Cascade in both the model and the database, or in neither
    3. Defining Relationships Between Entities
      1. The CLR Way: Setting a Navigation Property
      2. Setting an EntityReference Using an EntityKey
      3. Loading, Adding, and Attaching Navigation Properties
        1. Rules, rules, rules
      4. EntityReference.Load and EntityCollection.Load
        1. Load provides behind-the-scenes query creation and execution
        2. Understanding why Load cannot be called on Added entities
      5. EntityCollection.Add
        1. Adding new entities that are detached
        2. Adding new or existing entities that are attached
        3. Adding entities to the EntityCollection of a detached object
      6. Attach and Remove
        1. Use Attach only when a relationship exists in the data store
      7. Attach Versus Add
      8. Moving an Entity to a New Graph
    4. Learning a Few Last Tricks to Make You a Relationship Pro
      1. Using CreateSourceQuery to Enhance Deferred Loading
      2. Getting a Foreign Key Value
    5. Summary
  20. 16. Making It Real: Connections, Transactions, Performance, and More
    1. EntityConnection and Database Connections in the Entity Framework
      1. EntityConnection Versus Database Connection
      2. Programming EntityConnection Strings
      3. Using the EntityConnectionStringBuilder Class
        1. Dynamic EntityConnections
      4. Opening and Closing Entity and Database Connections
        1. Manually opening and closing connections
        2. Default behavior 1: Many calls on a single connection
          1. Default behavior 2: Multiple connections
          2. Forcing an explicit connection
          3. Connection versus Connection.StoreConnection
      5. Taking Control of How Store Connections Are Disposed
      6. What About Connection Pooling?
    2. The Entity Framework and Transactions
      1. Why Use Your Own Transaction?
      2. Understanding the Entity Framework’s Default: Implicit Transactions
        1. Where did the transaction come from?
        2. Controlling AcceptAllChanges in a transaction
      3. Specifying Your Own Transaction
      4. Reading Queries Using System.Transaction or EntityTransaction
      5. Can You Use Transactions Within ObjectContext?
    3. The Entity Framework and Security
      1. SQL Injection
        1. You’re safe with LINQ, but be careful with Entity SQL
        2. Entity SQL injection
      2. Protecting Data from Connection Piggybacks
    4. The Entity Framework and Performance
      1. A Few “Backyard Benchmarks”
        1. Interpreting the tests
      2. Reducing the Cost of Query Compilation
      3. The EDM Generator for Precompiled Views (and More)
        1. What’s in a precompiled view code file?
        2. Precompiling views against an existing project
      4. Precompiled LINQ to Entities Queries
        1. LINQ to Entities compiled queries
      5. Query Plan Caching for Entity SQL
        1. Entity SQL querying with EntityClient versus Object Services
      6. What About Database Updates and Performance?
    5. Entities in Multithreaded Applications
      1. Forcing an ObjectContext to Use Its Own Thread
      2. Another Spin on Threading: Concurrent Processing
    6. Summary
  21. 17. Controlling Objects with ObjectStateManager and MetadataWorkspace
    1. Managing ObjectStateEntry Objects with ObjectStateManager
      1. An ObjectStateEntry Refresher
    2. Getting an ObjectStateManager and Its Entries
      1. Getting Groups of Entries with GetObjectStateEntries
        1. Overloading GetObjectStateEntries using extension methods
      2. Getting a Single Entry with GetObjectStateEntry and TryGetObjectStateEntry
      3. Digging Through ObjectStateEntry
    3. CurrentValues and OriginalValues
      1. CurrentValueRecord.DataRecordInfo
    4. Building the ObjectStateEntry Visualizer
      1. Setting Up the Project and Code File
      2. Retrieving an ObjectStateEntry Using an EntityKey
      3. Reading the OriginalValues and CurrentValues of an ObjectStateEntry
      4. Determining Whether a Property Has Been Modified
      5. Displaying the ObjectStateEntry’s State and Entity Type
      6. Getting ComplexType Properties Out of ObjectStateEntry
      7. Modifying Values with ObjectStateManager
      8. Working with Relationships in ObjectStateManager
        1. RelationshipEntry EntityState
        2. Inspecting the RelationshipEntries
        3. Locating relationships for an entity
        4. Building graphs directly with the RelationshipManager
    5. ObjectStateManager and SavingChanges
      1. The FieldMetadata Hierarchy
    6. The MetadataWorkspace API
      1. Loading the MetadataWorkspace
        1. Creating a MetadataWorkspace without an EntityConnection
      2. Clearing the MetadataWorkspace from Memory
      3. The MetadataWorkspace ItemCollections
      4. ItemCollections Are Loaded as Needed with EntityCollection
        1. GetItemCollection/TryGetItemCollection
      5. Reading Metadata from the MetadataWorkspace
        1. GetItems/TryGetItems
        2. GetItem/TryGetItem
        3. GetFunctions/TryGetFunctions
      6. Querying the Items
      7. Building Entity SQL Queries Dynamically Using Metadata
      8. Reading the Results of a Dynamically Created Query
      9. Dynamic Entity SQL and Generics for Reference Lists
    7. 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
    8. Creating Entities and Graphs Dynamically
      1. Calling the AddChildtoParentObject Method
    9. Summary
  22. 18. Handling Entity Framework Exceptions
    1. Preparing for Exceptions in Entity Framework Code
    2. 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. Query Compilation Exceptions
      1. Invalid LINQ to Entities Query Expressions: System.NotSupportedException
      2. Invalid Entity SQL Query Expressions: EntitySQLException
      3. Store Provider Issues: EntityCommandCompilationException
    4. Creating a Common Wrapper to Handle Query Execution Exceptions
    5. SaveChanges Command Execution Exceptions
      1. Model and Mapping Constraints Are Broken: UpdateException
      2. Exceptions Thrown by Broken Constraints in the Database
      3. Automatically Rolling Back SaveChanges When an UpdateException Occurs
    6. ObjectStateEntries Returned by Object Services Exceptions
      1. General Entity Exceptions That May Occur When Executing Queries or Commands
    7. InvalidOperationExceptions
    8. Exceptions When Multiple Parties Edit Data Concurrently
      1. Handling Concurrency Conflicts
    9. 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 for Concurrency Checks
    10. 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
    11. Handling OptimisticConcurrencyExceptions
      1. Using ObjectContext.Refresh
      2. Using ClientWins Refresh
      3. Using StoreWins Refresh
      4. Refreshing Collections of Entities
      5. Refreshing Related Entities in a Graph
      6. Rewinding and Starting Again, and Maybe Again After That
      7. What If a Relationship, But No Scalar Properties, Changes?
      8. Reporting an Exception
    12. Handling Concurrency Exceptions at a Lower Level
      1. Handling Granular Exceptions Without User Intervention
      2. Handling Multiple Conflicts
        1. Separating the good from the bad
    13. Handling Exceptions When Transactions Are Your Own
    14. Summary
  23. 19. Using Your Own Custom Classes
    1. Mapping Classes to the Entity Data Model
      1. Mapping Rules for Custom Classes and Their Properties
      2. Inheriting from EntityObject
      3. Metadata Attributes
      4. Entity Classes
      5. Scalar Properties
      6. Navigation Properties
        1. EntityCollection navigation properties
        2. EntityReference navigation properties
      7. Mapping the Remaining Entities in the Model
      8. Mapping the EntityContainer
      9. Resolving Conflicts Between Custom Classes and Designer-Generated Classes
      10. Querying Using the Custom Classes
    2. Implementing the IPOCO Interfaces
      1. The IEntityWithKey Interface
      2. The IEntityWithChangeTracker Interface
        1. An EntityState property
      3. The IEntityWithRelationships Interface
      4. Working with the IPOCO-Enabled Objects
    3. Custom Class Assemblies and Entity Data Model Files
      1. Accessing the Model Files When They Are Not in a Referenced Assembly
    4. Summary
  24. 20. Using the Entity Framework in n-Tier Client-Side Applications
    1. Thinking in Layers
      1. Organizing Your Layers
    2. Finding Your Motivation: A Master/Detail Data Entry Form That Will Use the DataBridge Class
    3. Preventing Non-UI Logic from Leaking into the UI
    4. Implementing Logic That Fits Best in the Entity Partial Classes
      1. Creating an IsDirty Property for the ObjectContext
    5. Building the CommandExecutor Class
    6. Building the DataBridge Class
      1. Using a Long-Running ObjectContext
      2. Implementing the Primary Elements of the DataBridge Class
      3. Creating a Class for Lightweight Objects to Be Used in UI Pick Lists
      4. Creating the Main Entity Pick List: For Customer Names
      5. Using MergeOptions to Cache or Refresh a Pick List
      6. Building a Frequently Used Entity Graph for the UI
        1. Precompiling a frequently used query
        2. Some decisions that drove the design of the GetCustomerwithRelatedData method
        3. Converting a noncustomer to a customer
      7. Supplying Additional Lists for UI Drop-Downs
        1. Choosing between complete entities and narrower types for lists
      8. Saving Changes
      9. Rolling Back User Changes
        1. Considering in-memory rollbacks
        2. Keeping it simple: Rolling back from the database if you can
    7. Using the DataBridge Class for Data Binding in a Master/Detail Form
      1. Using BindingSourceControls with the DataBridge
      2. Instantiating the DataBridge Class in the Form
      3. Populating the Form with an Entity and Its Related Data
      4. Consuming the Pick Lists in the Form
      5. Deleting from Grids When EntityCollections and Referential Constraints Are Involved
        1. Deleting children from a grid is easier when the child has a composite key
        2. Deleting child entities in a grid when no referential constraint exists in the CSDL
    8. Allowing Users to Roll Back Their Edits
    9. Helping the User Who Forgets to Save Changes
    10. Summary
  25. 21. Using the Entity Framework in n-Tier ASP.NET Applications
    1. Understanding How an ObjectContext Fits into the Web Page Life Cycle
      1. Using EntityObjects in Read-Only Web Pages
      2. Exploring Options for Updating Entities in an ASP.NET Application
        1. Single or batch updates?
        2. Persist entities or use independent values?
      3. Evaluating ASP.NET’s State Solutions Against the Entity Framework
        1. View State
        2. Application cache and session state
    2. Introducing ASP.NET’s ObjectDataSource Control
      1. Why ObjectDataSource?
      2. ObjectDataSource Enforces Its Rules on Your Objects
      3. How the ObjectDataSource Gets Data into and out of the Data-Binding Controls
    3. Designing Object Provider Classes to Be Used with an ObjectDataSource
      1. Creating the CustomerProvider Class
      2. Creating the AddressProvider Class
      3. Creating the ReservationsProvider Class
      4. Providing Reusable, Cached Reference Lists
    4. Wiring Up the Provider Classes to ObjectDataSource Controls
      1. Using the ObjectDataSource Wizard to Perform the Initial Wiring to the Provider Classes
      2. Tweaking ObjectDataSource Properties to Work with Entities
        1. Getting the object to the entity provider
        2. Providing original and current values for updates
      3. Using ObjectDataSource Events to Solve Problems That Are Particular to Entities
        1. Inserting and updating entities that contain EntityReferences
        2. Editing EntityReference navigation properties
        3. Updating EntityReference navigation properties
        4. Inserting records with EntityReference properties
    5. Understanding Why We Didn’t Use Object Graphs in This Business Layer
      1. Database Hits Versus Very Busy Memory
    6. Summary
  26. 22. Implementing a Smarter WCF Service for Working with Entities
    1. Will Your Client Agree to Your Data Contract?
    2. Shipping DTOs, Not EntityObjects
      1. Building a Data Transfer Object to Take the Place of an Entity Object
        1. Replacing EntityReference navigation properties
        2. Replacing EntityCollection navigation properties
    3. Creating EntityState Properties That Do Not Rely on ObjectContext
      1. The EntityStateLocal Enums and Interface
      2. Implementing the IEntityStateLocal Interface in the DTO Classes
      3. Implementing the IEntityStateLocal Interface in the Entity Classes
    4. Designing the Service Interface
    5. Implementing the Service Operations
      1. Returning CustomerList as ShortCustomers with GetCustomerList
      2. Returning Additional Reference Lists
      3. Returning a Single Entity Graph for Editing with GetCustomer
      4. Building Methods to Create DTOs from Entity Objects
      5. Initializing the DTO Children
      6. Saving Edits Sent Back from the Client with SaveCustomer
      7. Building the Main Method for Updating the Graph: SaveCustomer
      8. UpdateChildren
    6. Implementing the Client That Will Use the WCF Service
      1. Rules for the Client to Follow
      2. Building a Business Layer Between the UI and the Services
      3. What’s in These Business Classes?
        1. The class constructor
        2. The property changed event
        3. The Initialize method
      4. Calling the Service Operations from the Business Layer
    7. Testing It All with a Simple Console Application
    8. Summary
  27. 23. The Entity Framework, Today and Tomorrow
    1. What About Building Reports with the Entity Framework?
      1. Major Differences Between the Entity Framework and LINQ to SQL
        1. The future of LINQ to SQL
        2. Migrating LINQ to SQL to the Entity Framework
    2. Extensions, Samples, and Solutions from Microsoft
      1. Extensions and APIs
        1. EFExtensions
        2. POCO Adapter for version 1
        3. Entity Framework Lazy Loading
        4. eSqlBlast
      2. Samples
        1. Entity Framework Query Samples
        2. Sample EDMX Code Generator
        3. Entity Framework Sample Provider
      3. Learning Tools
    3. Entity Framework v.Next
      1. The Transparent Design Process for the Next Version
    4. Blogs, Forums, and Other Resources
  28. A. Entity Framework Assemblies and Namespaces
    1. Unpacking the Entity Framework Files
    2. Exploring the Namespaces
      1. Existing Namespaces That Have New Classes and Functionality
      2. New Namespaces
  29. Index
  30. About the Author
  31. Colophon
  32. Copyright