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

Entity Framework 4.0 Recipes pdf

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 (19.6 MB, 649 trang )

Tenny
Hirani
Entity Framework 4.0 Recipes
Companion
eBook Available
Entity
Framework 4.0

Recipes

A Problem-Solution Approach
7.5 x 9.25 spine = 1.21875" 648 page count
THE EXPERT’S VOICE
®
IN .NET
Larry Tenny and Zeeshan Hirani
Ready-made solutions for putting Microsoft Entity
Framework 4.0 to work in your own applications
this print for content only—size & color not accurate
CYAN
MAGENTA
YELLOW
BLACK
PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Larry Tenny
Shelve in:
Microsoft .NET
User level:
Intermediate–Advanced


THE APRESS ROADMAP
Pro
Entity Framework 4.0
Pro LINQ: Language
Integrated Query
in C# 2010
Introducing .NET 4.0
with
Visual Studio 2010
Beginning
SQL Server 2008
for Developers
Entity Framework
Recipes
Expert
SQL Server 2008
Development
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN 978-1-4302-2703-8
9 781430 227038
5 49 9 9
Entity Framework 4.0 Recipes:
A Problem-Solution Approach
Dear Reader,
You want to start using Entity Framework 4.0, but you’re a little overwhelmed by

all the new terms and concepts. Want to get started right away? You’ve come to the
right place.
Entity Framework is Microsoft’s core data access technology. It represents a
completely new way to build data-driven applications. Here in this book you’ll find
well over a hundred recipes that help you get started with Entity Framework and
solve problems without having to wade through chapter after chapter of terminol-
ogy and theory.
Want to create your first model? We’ve got recipes for that. Want to model Table
per Type inheritance? We’ve got recipes for that. Want to use Entity Framework with
Windows Communication Foundation? We’ve got recipes for that! If you have a
problem, we have a short, to-the-point recipe that will give you the solution and a
clear explanation of how it works.
This book assumes just a basic knowledge of databases and .NET development.
You don’t need to be an expert developer or database administrator to use these
recipes. Each recipe provides a clear statement of the problem it solves. That way,
you can quickly scan for your problem and get right to the solution. We give you
step-by-step directions and provide a complete working example in each recipe.
The recipes are completely independent so you never have to flip around trying to
tie together a complete concept.
Entity Framework is Microsoft’s key data-enabling technology for now and for
years to come. With Microsoft’s Entity Framework, Visual Studio 2010, .NET 4.0,
and this book, you’re all set to develop some incredibly powerful applications using
the latest technologies and practices on the planet. We hope you enjoy the book.
Larry Tenny and Zeeshan Hirani
Zeeshan Hirani

Entity Framework 4.0 Recipes
A Problem-Solution Approach

Larry Tenny

Zeeshan Hirani
Entity Framework 4.0 Recipes: A Problem-Solution Approach
Copyright © 2010 by Larry Tenny and Zeeshan Hirani
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-2703-8
ISBN-13 (electronic): 978-1-4302-2704-5
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of
a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark
owner, with no intention of infringement of the trademark.
Publisher and President: Paul Manning
Lead Editor: Jonathan Gennick
Technical Reviewers: David Annesley-DeWinter, Brian Swan
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan
Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper,
Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom
Welsh
Coordinating Editor: Mary Tobin
Copy Editor: Nancy Sixsmith
Compositor: Bytheway Publishing Services
Indexer: Toma Mulligan
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail
, or
visit www.springeronline.com.
For information on translations, please e-mail , or visit www.apress.com.

Apress and friends of ED
books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special
Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in
this book is distributed on an “as is” basis, without warranty. Although every precaution
has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to
any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly
by the information contained in this work.
You can download the examples from the book’s catalog page:
/>Look for
the “Source Code” link underneath the cover image. You will need to answer questions pertaining
to this book in order to successfully download the code.
To the most important people in my life, my wife and kids.
– Larry
I would like to dedicate this book to my parents for encouraging me and supporting me always. Special thanks
to my Dad for his great love and support in everything.
– Zeeshan
 CONTENTS
Contents at a Glance
 Contents at a Glance iv
 Contents v
 About the Authors xxx
 About the Technical Reviewers xxxi
 Acknowledgments xxxii
 Preface xxxiii
 Chapter 1: Getting Started With Entity Framework 1
 Chapter 2: Entity Data Modeling Fundamentals 9
 Chapter 3: Querying an Entity Data Model 63
 Chapter 4: Using Entity Framework in ASP.NET 115

 Chapter 5: Loading Entities and Navigation Properties 155
 Chapter 6: Beyond the Basics with Modeling and Inheritance 189
 Chapter 7: Working with Object Services 251
 Chapter 8: Plain Old CLR Objects 271
 Chapter 9: Using the Entity Framework in N-Tier Applications 311
 Chapter 10: Stored Procedures 359
 Chapter 11: Functions 393
 Chapter 12: Customizing Entity Framework Objects 429
 Chapter 13: Improving Performance 471
 Chapter 14: Concurrency 509
 Chapter 15: Advanced Modeling 529
 Index 591
iv
v
Contents
 Contents at a Glance iv
 Contents v
 About the Authors xxx
 About the Technical Reviewers xxxi
 Acknowledgments xxxii
 Preface xxxiii
Who This Book Is For xxxiii
What’s in This Book xxxiv
About the Recipes xxxv
Stuff You Need to Get Started xxxvi
Code Examples xxxvi
The Database xxxvi
Apress Website xxxvii
 Chapter 1: Getting Started With Entity Framework 1
A Brief Tour of the Entity Framework World 2

Models 2
Terminology 3
Code 4
Visual Studio 2010 4
Using Entity Framework 5
 CONTENTS
vi
 Chapter 2: Entity Data Modeling Fundamentals 9
2-1. Creating a Simple Model 9
Problem 9
Solution 9
How It Works 14
2-2. Creating a Model from an Existing Database 16
Problem 16
Solution 16
How It Works 19
2-3. Modeling a Many-to-Many Relationship with No Payload 22
Problem 22
Solution 22
How It Works 23
2-4. Modeling a Many-to-Many Relationship with a Payload 26
Problem 26
Solution 26
How It Works 27
2-5. Modeling a Self-Referencing Relationship 29
Problem 29
Solution 29
How It Works 30
2-6. Splitting an Entity Across Multiple Tables 33
Problem 33

Solution 33
How It Works 35
2-7. Splitting a Table Across Multiple Entities 37
Problem 37
Solution 37
 CONTENTS
vii
How It Works 40
2-8. Modeling Table per Type Inheritance 42
Problem 42
Solution 42
How It Works 44
2-9. Using Conditions to Filter an ObjectSet 46
Problem 46
Solution 46
How It Works 48
2-10. Modeling Table per Hierarchy Inheritance 49
Problem 49
Solution 49
How It Works 52
2-11. Modeling Is-a and Has-a Relationships Between Two Entities 54
Problem 54
Solution 55
How It Works 56
2-12. Creating, Modifying, and Mapping Complex Types 57
Problem 57
Solution 58
How It Works 59
 Chapter 3: Querying an Entity Data Model 63
3-1. Executing an SQL Statement 63

Problem 63
Solution 63
How It Works 65
3-2. Returning Objects from a SQL Statement 66
Problem 66
 CONTENTS
viii
Solution 66
How It Works 67
3-3. Returning Objects from an Entity SQL Statement 68
Problem 68
Solution 68
How It Works 70
3-4. Specifying Fully Qualified Names in Entity SQL 71
Problem 71
Solution 72
How It Works 74
3-5. Finding a Master that Has Detail in a Master-Detail Relationship 74
Problem 74
Solution 74
How It Works 76
3-6. Setting Default Values in a Query 77
Problem 77
Solution 77
How It Works 79
3-7. Returning Multiple Result Sets From a Stored Procedure 80
Problem 80
Solution 80
How It Works 81
3-8. Comparing Against a List of Values 82

Problem 82
Solution 82
How It Works 84
3-9. Building and Executing a Query Against an ObjectSet<T> 85
Problem 85
 CONTENTS
ix
Solution 85
How It Works 87
3-10. Returning a Primitive Type From a Query 87
Problem 87
Solution 87
How It Works 89
3-11. Filtering Related Entities 89
Problem 89
Solution 89
How It Works 92
3-12. Applying a Left Outer Join 93
Problem 93
Solution 93
How It Works 95
3-13. Ordering by Derived Types 96
Problem 96
Solution 96
How It Works 97
3-14. Paging and Filtering 98
Problem 98
Solution 98
How It Works 100
3-15. Grouping by Date 101

Problem 101
Solution 101
How It Works 102
3-16. Flattening Query Results 103
Problem 103
 CONTENTS
x
Solution 103
How It Works 105
3-17. Grouping by Multiple Properties 105
Problem 105
Solution 106
How It Works 108
3-18. Using Bitwise Operators in a Filter 108
Problem 108
Solution 108
How It Works 111
3-19. Joining on Multiple Columns 111
Problem 111
Solution 111
How It Works 113
 Chapter 4: Using Entity Framework in ASP.NET 115
4-1. Building a Search Query 115
Problem 115
Solution 115
How It Works 118
4.2. Building CRUD Operations in an ASP.NET Web Page 119
Problem 119
Solution 119
How It Works 124

4-3. Executing Business Logic When Changes Are Saved 124
Problem 124
Solution 124
How It Works 126
4-4. Loading Related Entities 127
 CONTENTS
xi
Problem 127
Solution 127
How It Works 129
4-5. Searching with QueryExtender 129
Problem 129
Solution 129
How It Works 135
4-6. Retrieving a Derived Type Using an EntityDataSource Control 136
Problem 136
Solution 136
How It Works 139
4-7. Filtering with ASP.NET’s URL Routing 139
Problem 139
Solution 139
How It Works 142
4-8. Building CRUD Operations with an ObjectDataSource Control 143
Problem 143
Solution 143
How It Works 148
4-9. Using Entity Framework With MVC 149
Problem 149
Solution 149
How It Works 154

 Chapter 5: Loading Entities and Navigation Properties 155
5-1. Loading Related Entities 155
Problem 155
Solution 155
How It Works 158
 CONTENTS
xii
5-2. Loading a Complete Object Graph 160
Problem 160
Solution 160
How It Works 162
5-3. Loading Navigation Properties on Derived Types 162
Problem 162
Solution 163
How It Works 164
5-4. Using Include() with Other LINQ Query Operators 165
Problem 165
Solution 165
How It Works 166
5-5. Deferred Loading of Related Entities 167
Problem 167
Solution 167
How It Works 169
5-6. Filtering and Ordering Related Entities 169
Problem 169
Solution 170
How It Works 171
5-7. Executing Aggregate Operations on Related Entities 172
Problem 172
Solution 172

How It Works 174
5-8. Testing Whether an Entity Reference or Entity Collection Is Loaded 174
Problem 174
Solution 174
How It Works 176
 CONTENTS
xiii
5-9. Loading Related Entities Explicitly 176
Problem 176
Solution 176
How It Works 178
5-10. Filtering an Eagerly Loaded Entity Collection 180
Problem 180
Solution 180
How It Works 181
5-11. Using Relationship Span 182
Problem 182
Solution 182
How It Works 184
5-12. Modifying Foreign Key Associations 184
Problem 184
Solution 184
How It Works 187
 Chapter 6: Beyond the Basics with Modeling and Inheritance 189
6-1. Retrieving the Link Table in a Many-to-Many Association 189
Problem 189
Solution 189
How It Works 191
6-2. Exposing a Link Table as an Entity 192
Problem 192

Solution 192
How It Works 195
6-3. Modeling a Many-to-Many, Self-Referencing Relationship 196
Problem 196
Solution 196
 CONTENTS
xiv
How It Works 197
6-4. Modeling a Self-Referencing Relationship Using Table per Hierarchy Inheritance200
Problem 200
Solution 200
How It Works 202
6-5. Modeling a Self-Referencing Relationship and Retrieving a Complete Hierarchy .204
Problem 204
Solution 204
How It Works 207
6-6. Mapping Null Conditions in Derived Entities 208
Problem 208
Solution 208
How It Works 209
6-7. Modeling Table per Type Inheritance Using a Non-Primary Key Column 211
Problem 211
Solution 211
How It Works 215
6-8. Modeling Nested Table per Hierarchy Inheritance 216
Problem 216
Solution 216
How It Works 218
6-9. Limiting the Values Assigned to a Foreign Key 220
Problem 220

Solution 220
How It Works 222
6-10. Applying Conditions in Table per Type Inheritance 224
Problem 224
Solution 224
 CONTENTS
xv
How It Works 225
6-11. Creating a Filter on Multiple Criteria 227
Problem 227
Solution 227
How It Works 229
6-12. Using Complex Conditions with Table per Hierarchy Inheritance 232
Problem 232
Solution 233
How It Works 235
6-13. Modeling Table per Concrete Type Inheritance 238
Problem 238
Solution 238
How It Works 240
6-14. Applying Conditions on a Base Entity 242
Problem 242
Solution 242
How It Works 244
6-15. Creating Independent and Foreign Key Associations 246
Problem 246
Solution 246
How It Works 247
6-16. Changing an Independent Association into a Foreign Key Association 247
Problem 247

Solution 248
How It Works 249
 Chapter 7: Working with Object Services 251
7-1. Dynamically Building a Connection String 251
Problem 251
 CONTENTS
xvi
Solution 251
How It Works 252
7-2. Reading a Model from a Database 253
Problem 253
Solution 253
How It Works 256
7-3. Deploying a Model 257
Problem 257
Solution 257
How It Works 257
7-4. Using the Pluralization Service 258
Problem 258
Solution 258
How It Works 260
7-5. Retrieving Entities from the Object State Manager 261
Problem 261
Solution 261
How It Works 263
7-6. Generating a Model from the Command Line 263
Problem 263
Solution 263
How It Works 264
7-7. Working with Dependent Entities in an Identifying Relationship 264

Problem 264
Solution 264
How It Works 267
7-8. Inserting Entities Using an Object Context 267
Problem 267
 CONTENTS
xvii
Solution 267
How It Works 269
 Chapter 8: Plain Old CLR Objects 271
8-1. Using POCO 271
Problem 271
Solution 271
How It Works 276
8-2. Loading Related Entities With POCO 276
Problem 276
Solution 276
How It Works 279
8-3. Lazy Loading With POCO 279
Problem 279
Solution 280
How It Works 282
8-4. POCO With Complex Type Properties 283
Problem 283
Solution 283
How It Works 285
8-5. Notifying Entity Framework About Object Changes 286
Problem 286
Solution 286
How It Works 288

8-6. Retrieving the Original (POCO) Object 289
Problem 289
Solution 289
How It Works 291
8-7. Manually Synchronizing the Object Graph and the Object State Manager 292
 CONTENTS
xviii
Problem 292
Solution 292
How It Works 295
8-8. Testing Domain Objects 296
Problem 296
Solution 296
How It Works 304
8-9. Testing a Repository Against a Database 305
Problem 305
Solution 305
How It Works 308
 Chapter 9: Using the Entity Framework in N-Tier Applications 311
9-1. Deleting an Entity When Disconnected 311
Problem 311
Solution 311
How It Works 314
9-2. Managing Concurrency When Disconnected 315
Problem 315
Solution 315
How It Works 318
9-3. Finding Out What Has Changed 319
Problem 319
Solution 319

How It Works 322
9-4. Using POCO With WCF 323
Problem 323
Solution 323
How It Works 328
 CONTENTS
xix
9-5. Using Self-Tracking Entities With WCF 329
Problem 329
Solution 329
How It Works 333
9-6. Validating Self-Tracking Entities 334
Problem 334
Solution 334
How It Works 338
9-7. Using Self-Tracking Entities on the Server Side 338
Problem 338
Solution 338
How It Works 344
9-8. Serializing Proxies in a WCF Service 345
Problem 345
Solution 345
How It Works 349
9-9. Serializing Self-Tracking Entities in the ViewState 349
Problem 349
Solution 349
How It Works 353
9-10. Fixing Duplicate References on a WCF Client 354
Problem 354
Solution 354

How It Works 357
 Chapter 10: Stored Procedures 359
10-1. Returning an Entity Collection 359
Problem 359
Solution 359
 CONTENTS
xx
How It Works 361
10-2. Returning Output Parameters 362
Problem 362
Solution 362
How It Works 365
10-3. Returning a Scalar Value Result Set 365
Problem 365
Solution 365
How It Works 367
10-4. Returning a Complex Type from a Stored Procedure 367
Problem 367
Solution 367
How It Works 369
10-5. Defining a Custom Function in the Storage Model 370
Problem 370
Solution 370
How It Works 372
10-6. Populating Entities in a Table per Type Inheritance Model 373
Problem 373
Solution 373
How It Works 375
10-7. Populating Entities in a Table per Hierarchy Inheritance Model 376
Problem 376

Solution 376
How It Works 378
10-8. Mapping the Insert, Update, and Delete Actions to Stored Procedures 379
Problem 379
Solution 379
 CONTENTS
xxi
How It Works 381
10-9. Using Stored Procedures for the Insert and Delete Actions in a Many-to-Many
Association 382
Problem 382
Solution 383
How It Works 387
10-10. Mapping the Insert, Update, and Delete Actions to Stored Procedures for Table
per Hierarchy Inheritance 387
Problems 387
Solution 387
How It Works 391
 Chapter 11: Functions 393
11-1. Returning a Scalar Value from a Model Defined Function 393
Problem 393
Solution 393
How It Works 396
11-2. Filtering an Entity Collection Using a Model Defined Function 397
Problem 397
Solution 397
How It Works 400
11-3. Returning a Computed Column from a Model Defined Function 401
Problem 401
Solution 401

How It Works 404
11-4. Calling a Model Defined Function from a Model Defined Function 404
Problem 404
Solution 404
How It Works 408
11-5. Returning an Anonymous Type From a Model Defined Function 408
 CONTENTS
xxii
Problem 408
Solution 408
How It Works 411
11-6. Returning a Complex Type From a Model Defined Function 412
Problem 412
Solution 412
How It Works 415
11-7. Returning a Collection of Entity References From a Model Defined Function 415
Problem 415
Solution 415
How It Works 417
11-8. Using Canonical Functions in eSQL 418
Problem 418
Solution 418
How It Works 419
11-9. Using Canonical Functions in LINQ 419
Problem 419
Solution 419
How It Works 421
11-10. Calling Database Functions in eSQL 422
Problem 422
Solution 422

How It Works 424
11-11. Calling Database Functions in LINQ 424
Problem 424
Solution 424
How It Works 425
11-12. Defining Built-in Functions 425
 CONTENTS
xxiii
Problem 425
Solution 426
How It Works 428
 Chapter 12: Customizing Entity Framework Objects 429
12-1. Executing Code When SaveChanges() Is Called 429
Problem 429
Solution 429
How It Works 431
12-2. Validating Property Changes 432
Problem 432
Solution 432
How It Works 434
12-3. Logging Database Connections 435
Problem 435
Solution 435
How It Works 437
12-4. Recalculating a Property Value When an Entity Collection Changes 437
Problem 437
Solution 437
How It Works 439
12-5. Automatically Deleting Related Entities 440
Problem 440

Solution 440
How It Works 443
12-6. Deleting All Related Entities 443
Problem 443
Solution 444
How It Works 447

×