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