Tải bản đầy đủ (.pdf) (914 trang)

Oreilly programming entity framework 2nd edition aug 2010

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.59 MB, 914 trang )

Download from Library of Wow! eBook <www.wowebook.com>


Download from Library of Wow! eBook <www.wowebook.com>


SECOND EDITION

Programming Entity Framework

Julia Lerman

Beijing • Cambridge • Farnham • Kưln • Sebastopol • Taipei • Tokyo

Download from Library of Wow! eBook <www.wowebook.com>


Programming Entity Framework, Second Edition
by Julia Lerman
Copyright © 2010 Julia Lerman. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (). For more information, contact our
corporate/institutional sales department: 800-998-9938 or

Editors: Mike Hendrickson and Laurel Ruma
Production Editor: Loranah Dimant
Copyeditor: Audrey Doyle
Proofreader: Sada Preisch


Indexer: Ellen Troutman Zaig
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano

Printing History:
February 2009:
August 2010:

First Edition.
Second Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of
O’Reilly Media, Inc. Programming Entity Framework, the image of a Seychelles blue pigeon, and related
trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a
trademark claim, the designations have been printed in caps or initial caps.
.NET is a registered trademark of Microsoft Corporation.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

ISBN: 978-0-596-80726-9
[SB]
1281106344

Download from Library of Wow! eBook <www.wowebook.com>


Table of Contents


Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
1. Introducing the ADO.NET Entity Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
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
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
3

6
7
8
9
9
10
10
11
12
12
13
13
14
14
15
15
15
16
16
17

2. Exploring the Entity Data Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Why Use an Entity Data Model?

19

iii

Download from Library of Wow! eBook <www.wowebook.com>



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
Associations
Navigation Property
Navigation Properties That Return Collections
SSDL: The Store Schema
MSL: The Mappings
Database Views in the EDM
Summary

20
21
24
26
26
27
29
31

31
33
34
35
36
38
41
42
43
45
46
47

3. Querying Entity Data Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Query the Model, Not the Database
Your First EDM Query
Where Did the Context and Classes Come From?
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
The Parameterized ObjectQuery
Querying with Methods
Querying with LINQ Methods
Querying with Query Builder Methods and Entity SQL
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

iv | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

49
50
51
55
55
57
57
58
60
61
61
64
66
66
68
70
71
71
71
71

72


Avoiding Inadvertent Query Execution
Summary

74
75

4. Exploring LINQ to Entities in Greater Depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
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
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
Filtering and Sorting with EntityCollections
Aggregates with EntityCollections
Aggregates in LINQ Methods
Joins and Nested Queries
Joins
Nested Queries
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
Explicitly Loading Entity Collections and Entity References
Using the Include Method to Eager-Load
Pros and Cons of Load and Include
Retrieving a Single Entity
Retrieving a Single Entity with GetObjectByKey
Finding More Query Samples
Summary

78
78
79
79
80
84
84
84
86
86
87
88
88
89
90
90
91

93
94
95
95
97
99
100
101
101
103
106
107
108
109
109

5. Exploring Entity SQL in Greater Depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Literals in Entity SQL
Expressing a DateTime Literal
Expressing a Decimal Literal
Using Additional Literal Types
Projecting in Entity SQL

111
112
112
112
113
Table of Contents | v


Download from Library of Wow! eBook <www.wowebook.com>


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

114
115
115
115
116
116

117
117
118
118
119
120
121
121
122
123
124
126
126
127

6. Modifying Entities and Saving Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
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

129
130
131
134
135
137

139

7. Using Stored Procedures with the EDM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Updating the Model from a Database
Working with Functions
Function Attributes
Mapping Functions to Entities
Mapping Insert, Update, and Delete Functions to an Entity
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
vi | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

142
143
144
146
148
152
153
155
156
158
159



Mapping a Function to a Scalar Type
Mapping a Function to a Complex Type
Summary

159
160
163

8. Implementing a More Real-World Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
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
Summary

166
168

168
170
172
172
174
175
176
178
181
182
183
184
185

9. Data Binding with Windows Forms and WPF Applications . . . . . . . . . . . . . . . . . . . 187
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

187
188
189
190
191
194
196
198
199
201
202
204
208
211
213
213
214
215
215

Table of Contents | vii

Download from Library of Wow! eBook <www.wowebook.com>



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
Editing Entities and Their Related Data
Using SortDescriptions to Keep Sorting in Sync with Data Modifications
Adding Items to the Child EntityCollection
The Last Task: Adding New Trips to the Catalog
Summary

216
218
219
222
224
225
226
227
230

10. Working with Object Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Where Does Object Services Fit into the Framework?
Processing Queries
Parsing Queries: From Query to Command Tree to SQL
Understanding Query Builder Methods
Analyzing a Query with ObjectQuery Methods and Properties
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
Taking Control of ObjectState
ObjectStateManager Methods
ObjectStateEntry State Methods for Managing State
ObjectSet State Methods
Sending Changes Back to the Database
ObjectContext.SaveChanges
Affecting SaveChanges Default Behavior
Overriding SaveChanges Completely
Data Validation with the SavingChanges Event
Concurrency Management
Transaction Support
Implementing Serialization, Data Binding, and More
Object Services Supports XML and Binary Serialization
Object Services Supports Data Binding

viii | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

231
233

234
235
238
241
242
242
244
244
246
246
247
248
249
252
253
257
257
258
259
259
259
260
261
261
261
262
263
263
265



Summary

266

11. Customizing Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
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
The EntityObject.PropertyChanging
and EntityObject.PropertyChanged Events
The AssociationChanged Event
Creating Your Own Partial Methods and Properties
Overriding the Object Constructor
Overriding ObjectContext.SaveChanges
Creating Custom Properties
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
Customizing a Template for Major Class Modifications

Switching Between the Default Template and a Custom Template
Summary

267
269
269
271
273
274
275
276
280
282
284
284
285
286
289
290
291
292
292
293
295
295
296

12. Data Binding with RAD ASP.NET Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
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
EntityDataSource Context Events
EntityDataSource and ViewState

298
298
299
299
301
303
304
304
305
306
306

Table of Contents | ix

Download from Library of Wow! eBook <www.wowebook.com>


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


308
309
309
310
312
313
314
316
317
317
318
319
320
321
321
323
325
326
327
329
332

13. Creating and Using POCO Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Creating POCO Classes
Creating an ObjectContext Class to Manage the POCOs
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

x | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

336
339
341
341
341
342
342
342
343
344


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

345
346
346
347
348
350
354
358
359
359

14. Customizing Entity Data Models Using the EDM Designer . . . . . . . . . . . . . . . . . . . . 361
Mapping Table per Type Inheritance for Tables That Describe
Derived Types
Mapping TPT Inheritance
Querying Inherited Types
POCO Classes and Inherited Objects
Inserting TPT Inherited 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

362
363
365
366
366
368
370
371
373
375
376
378
380
381
383

385
385
387
388
389
390
391
392
393
393
394
396

Table of Contents | xi

Download from Library of Wow! eBook <www.wowebook.com>


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

397
398
399

399
399
399
400
401

15. Defining EDM Mappings That Are Not Supported by the Designer . . . . . . . . . . . . . 403
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

403
407
408
408
409
411
413
413

414
416
416
417

16. Gaining Additional Stored Procedure and View Support in the Raw XML . . . . . . . 419
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
xii | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

419
420
420

421
423
423
424
424
424
425
426
427
429
429
431
433


Creating Associations with the New Entity
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
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

437
438
440
440

441
444
445
445
447

17. Using EntityObjects in WCF Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
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

450
451
452
453
454
455
456
457
460
461
463
463
463
465
466
467
468
469
473
474
474

475
475
480
481
481
483
484
485

Table of Contents | xiii

Download from Library of Wow! eBook <www.wowebook.com>


Understanding How WCF RIA Services Relates to the Entity Framework
Summary

485
487

18. Using POCOs and Self-Tracking Entities in WCF Services . . . . . . . . . . . . . . . . . . . . . . 489
Creating WCF-Friendly POCO Classes
Updating the POCO Classes Based on the Current BreakAway Model
Isolating the POCO Entities in Their Own Project
Adding Custom Logic to the POCO Entities with a Base Class
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
Inspecting the Generated Context Class and Extensions
Using POCO Entities with WCF Data and RIA Services
Preparing for WCF Data Services
Using POCO Entities in WCF RIA Services
Sorting Out the Many Options for Creating Services
Summary

490
490
491
493
495
496
497
498
500
503
503
505
506
507
513
515
515
517

519
520

19. Working with Relationships and Associations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
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
Understanding Referential Integrity and Constraints
Implementing Deletes and Cascading Deletes
xiv | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

522
523
525
526
527

528
528
529
530
530
531
534
537
540


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
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

542
543
544

544
545
545
547
547
548
549
550
551
551
552
553

20. Real World Apps: Connections, Transactions, Performance, and More . . . . . . . . . . 555
Entity Framework and Connections
Overriding EntityConnection Defaults
Working with Connection Strings Programmatically
Opening and Closing Connections
Getting the Store Connection from EntityConnection
Disposing Connections
Pooling Connections
Fine-Tuning Transactions
Why Use Your Own Transaction?
Understanding Implicit Entity Framework Transactions
Specifying Your Own Read/Write Transactions
Specifying Your Own Read-Only Transactions
Rolling Back Transactions
Understanding Security
Guarding Against 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
Precompiling Views for Performance
Precompiling LINQ to Entities Queries for Performance
Fine-Tuning Updates for Performance?
Lacking Support for Full Text Searches
Exploiting Multithreaded Applications

555
556
557
560
562
562
563
564
564
565
566
569
570
571
571
573
574
575
579

580
580
582
585
589
590
591

Table of Contents | xv

Download from Library of Wow! eBook <www.wowebook.com>


Forcing an ObjectContext to Use Its Own Thread
Implementing Concurrent Thread Processing
Exploiting .NET 4 Parallel Computing
Summary

591
593
596
596

21. Manipulating Entities with ObjectStateManager and MetadataWorkspace . . . . . 597
Manipulating Entities and Their State with ObjectStateManager
Refreshing Your High-Level Understanding of ObjectStateEntry
Getting an ObjectStateManager and Its Entries
Building Extension Methods to Overload GetObjectStateEntries
Building a Method to Return Managed Entities
Using GetObjectStateEntry and TryGetObjectStateEntry

Mining Entity Details from ObjectStateEntry
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
Using the MetadataWorkspace
Loading the MetadataWorkspace
Clearing the MetadataWorkspace from Memory
Understanding the MetadataWorkspace ItemCollections
Retrieving Metadata from the MetadataWorkspace
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
Reading the Results of a Dynamically Created Query
Creating and Manipulating Entities Dynamically
Creating EntityObjects Without Entity Classes
Creating Entities and Graphs Dynamically
Summary

598
599
599

600
602
603
604
609
611
612
613
614
614
615
619
620
622
622
623
624
625
628
629
629
632
634
637
637
640
643

22. Handling Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
Preparing for Exceptions

Handling EntityConnectionString Exceptions

xvi | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>

645
647


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
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

648
648
649
649
649
650
652
652
654
654
655
656
656
657
658
658

23. Planning for Concurrency Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
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
Handling OptimisticConcurrencyExceptions
Using ObjectContext.Refresh
Using Refresh with ClientWins
Using Refresh with StoreWins

660
660
661
661
661
662
662
663
664
665
666
666
667
667
668
670
671
671
673


Table of Contents | xvii

Download from Library of Wow! eBook <www.wowebook.com>


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
Handling Exceptions When Transactions Are Your Own
Summary

673
675
676
678
678
678
680
682
683

24. Building Persistent Ignorant, Testable Applications . . . . . . . . . . . . . . . . . . . . . . . . 685
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
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
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
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

xviii | Table of Contents

Download from Library of Wow! eBook <www.wowebook.com>


686
687
687
689
689
693
695
697
698
699
702
703
706
708
710
712
714
714
716
716
718
720
721
722
723
723
724
725
725



25. Domain-Centric Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
Creating a Model and Database Using Model First
Creating a Conceptual Model in the Designer
Creating the Entities
Creating Association and Inheritance Hierarchies
Generating Database Schema from the Model
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

728
728
730
734
738
744
745
747
749
751
751

753
755
758
759

26. Using Entities in Layered Client-Side Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 761
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

762
764
766
768
772
773
774
778
779
781
782


27. Building Layered Web Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783
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
Comparing ASP.NET’s State Solutions to the Needs of the Entity
Framework
Building an N-Tier Web Forms Application
Designing the Application
Using the Existing Repositories

783
785
786
788
789
793
794
795

Table of Contents | xix

Download from Library of Wow! eBook <www.wowebook.com>


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

795
797
799
800
803
805
806
813
814
817
817
818

A. Entity Framework Assemblies and Namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821
B. Data-Binding with Complex Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825
C. Additional Details About Entity Data Model Metadata . . . . . . . . . . . . . . . . . . . . . . 831
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839

xx | Table of Contents


Download from Library of Wow! eBook <www.wowebook.com>


Foreword

I first met Julie Lerman (rhymes with “German”) while she was visiting the Microsoft
campus for a Software Design Review (SDR). An SDR is an event where we invite
customers we trust to be representative of a much larger crowd. In this particular case,
I was new to the SQL Server division and trying hard to catch up on the raft of technologies Microsoft shipped in the data space for developers. Julie, on the other hand,
was a seasoned veteran and not only knew the answers to all of my Entity Framework
questions but had already written a book on the topic. That book, Programming Entity
Framework, was the first edition of the book you’re now holding in your hands. Or, if
you are a .NET programmer, you know it simply as “THE book on EF.”
As the months went on, I ran into Julie more and more. She was researching the second
edition of her famous EF book. And by “researching,” I mean “pointing out our mistakes.” Julie was not only invaluable for teaching customers the real-world ins and outs
of EF, she had a way of asking questions about alphas and betas that made us rethink
what we were doing in many cases to improve the version of EF that ships with .NET
4 as well as the supporting functionality in Visual Studio 2010. And she was so well
respected because of her first EF book that anything she said received extra attention
from the EF team in ways I don’t see for many senior architects, let alone lowly program
managers. Julie had become an ad hoc member of the EF team itself.
My most recent encounter with Julie was by far the most fun. At a talk at the 2010
TechEd in New Orleans, I had the privilege of being Julie’s “code monkey,” which
meant mostly that I fetched her coffee, carried her bags, and wrote her code while she
entertained and educated a packed room. In 60 minutes, she did a tour de force tour
through nearly all the new features in EF 4.0, driving me through one complete demo
every 4 minutes. Normally, this would make an audience’s heads spin, but she has such
a grasp of the material and such a clear way of presenting it that she had everyone’s
rapt attention.

It’s this same completeness and clarity that you’ll find in this book, in chapters ranging
from the basics in the details you’ll need to write actual applications for your actual
business needs. If there is more material to lead you through the basics of the Entity
Framework and to be a continuing reference, I don’t know what it is.

xxi

Download from Library of Wow! eBook <www.wowebook.com>


During her presentation, Julie fielded questions on all manner of EF details and related
topics, but the one that made me cringe under the weight of history is the one I always
get, too: “Why should we use EF when Microsoft has already given us so many other
data access technologies?” Julie’s answer came without hesitation: “Because it’s the
best!”
Now, as a Microsoft employee sensitive to the needs of a wide-range of customers across
a wide-range of needs, I have to say that officially you should use the technology that
best fits your specific business problem. I can also say that the Entity Framework is
the .NET technology against which we’re placing all of our future bets and making all
of our biggest investments, which means that it’s the technology that we hope meets
most of your needs now and will meet more of your needs in the future.
But, I have to say, I do like Julie’s answer a great deal.
—Chris Sells, SQL Server division, Microsoft Corporation

xxii | Foreword

Download from Library of Wow! eBook <www.wowebook.com>


Preface


In June 2006, I was invited to attend a meet-up for data geeks at Tech Ed North America.
As the meet-up was early enough not to compete with the many fun evening parties at
Tech Ed, I happily crossed the lovely bridge between the Convention Center and the
hotel where the meeting was to take place.
Little did I know I was about to see a new technology from Microsoft’s Data Programmability team that was going to be the focus of my attention for the next few years.
In addition to other geeky discussions about data access, Pablo Castro, Mike Pizzo,
and Britt Johnson (all from Microsoft) talked to us about a new technology that was
coming in the next version of ADO.NET. It would allow developers to create their own
views of their database and query against these views rather than against the database.
As usual, Tech Ed was overwhelming, so as interesting as this new way of working with
data looked to me, I had to put it in a back corner of my mind and let it simmer for a
few months. I finally downloaded the preview and began playing with it. What was
most fun to me when I started exploring this technology, called Entity Framework, was
the lack of serious documentation, which forced me to play with all of its knobs and
dials to figure out what was in there and how it worked.
Unlike many in-development technologies from Microsoft, the Entity
Framework did not start off with a cool name as did WCF (née Indigo)
and ADO.NET Data Services (Astoria). Although it is often hard to give
up these early technology nicknames for their final (and relatively boring) names, the Entity Framework has had its “grown-up name” since
the beginning.

Over this time, it also became clear how important the Entity Framework and its underlying Entity Data Model are to Microsoft. They are a critical part of Microsoft’s
strategy for the data access that all of its products perform, whether this is the data that
Reporting Services uses to enable us to build reports, the data that comprises Workflow,
data in the cloud, or data that we developers want our .NET applications to access.

xxiii

Download from Library of Wow! eBook <www.wowebook.com>



×