1. Trang chủ
  2. » Công Nghệ Thông Tin

Programming Entity Framework, 2nd Edition doc

914 6,7K 2
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Programming Entity Framework, 2nd Edition
Tác giả Julia Lerman
Trường học O’Reilly Media, Inc.
Chuyên ngành Programming and Software Development
Thể loại sách hướng dẫn
Năm xuất bản 2010
Thành phố Sebastopol
Định dạng
Số trang 914
Dung lượng 13,66 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

489 Updating the POCO Classes Based on the Current BreakAway Model 490Isolating the POCO Entities in Their Own Project 491Adding Custom Logic to the POCO Entities with a Base Class 493 P

Trang 3

SECOND EDITION Programming Entity Framework

Julia Lerman

Trang 4

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 (http://my.safaribooksonline.com) For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.

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: First Edition

August 2010: 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 tained herein.

con-ISBN: 978-0-596-80726-9

[SB]

Trang 5

Table of Contents

Foreword xxi Preface xxiii

1 Introducing the ADO.NET Entity Framework 1

The Entity Relationship Model: Programming Against a Model,

The Entity Data Model: A Client-Side Data Model 3

What About ADO.NET DataSets and LINQ to SQL? 15

Entity Framework Pain Points Are Fading Away 16

2 Exploring the Entity Data Model 19

Trang 6

The EDM Within the Entity Framework 20

Navigation Properties That Return Collections 42

3 Querying Entity Data Models 49

Where Did the Context and Classes Come From? 51

Writing Your First LINQ to Entities Query 55Querying with Object Services and Entity SQL 57

Querying with Query Builder Methods and Entity SQL 64

ObjectQuery, ObjectSet, and LINQ to Entities 66Querying with EntityClient to Return Streamed Data 68EntityConnection and the Connection String 70

Translating Entity Queries to Database Queries 71Pay Attention to the NET Method’s Impact on Generated SQL 72

Trang 7

Avoiding Inadvertent Query Execution 74

4 Exploring LINQ to Entities in Greater Depth 77

LINQ Projections and Special Language Features 80

Filtering and Sorting with an EntityReference 86

Projecting Properties from EntityCollection Entities 87Filtering and Sorting with EntityCollections 88

Explicitly Loading Entity Collections and Entity References 101

Retrieving a Single Entity with GetObjectByKey 108

5 Exploring Entity SQL in Greater Depth 111

Trang 8

DbDataRecords and Nonscalar Properties 114

Filtering and Sorting with an EntityReference 116Filtering and Sorting with EntityCollections 116

Returning Entities from an Entity SQL GROUP BY Query 121

Using Include with an ObjectQuery and Entity SQL 123Understanding Entity SQL’s Wrapped and Unwrapped Results 124Entity SQL Rules for Wrapped and Unwrapped Results 126Digging a Little Deeper into EntityClient’s Results 126

6 Modifying Entities and Saving Changes 129

7 Using Stored Procedures with the EDM 141

Mapping Insert, Update, and Delete Functions to an Entity 148

Using the EDM Designer Model Browser to Import Additional

Mapping the First of the Read Stored Procedures: ContactsbyState 156

Avoiding Inadvertent Client-Side Processing 159

Trang 9

Mapping a Function to a Scalar Type 159

8 Implementing a More Real-World Model 165

Introducing the BreakAway Geek Adventures Business Model

Modifying the Names of Entities and Properties 170Resolving Collisions Between Property Names and Entity Names 172

Using the Use Original Value Checkbox in Update Mappings 176

Splitting Out the Model’s Metadata Files 184

9 Data Binding with Windows Forms and WPF Applications 187

Data Binding with Windows Forms Applications 187

Creating an Object Data Source for a Customer Entity 190Getting an Entity’s Details onto a Form 191Adding Code to Query an EDM When a Form Loads 194

Displaying the Properties of Related Data in the Grid 199

Editing Navigation Properties (and Shrinking the Query) 202Replacing the Navigation Property TextBoxes with ComboBoxes 204

Adding the Necessary Data Source Objects 215Inspecting the XAML and Code Generated by the Automated

Trang 10

Adding Code to Query the EDM When the Window Loads 216Customizing the Display of the Controls 218Selecting an Entity and Viewing Its Details 219Adding Another EntityCollection to the Mix 222Editing Entities and Their Related Data 224Using SortDescriptions to Keep Sorting in Sync with Data Modifica-

Adding Items to the Child EntityCollection 226The Last Task: Adding New Trips to the Catalog 227

10 Working with Object Services 231

Where Does Object Services Fit into the Framework? 231

Parsing Queries: From Query to Command Tree to SQL 234

Analyzing a Query with ObjectQuery Methods and Properties 238Executing Queries with ToList, ToArray, First or Single 241Executing Queries with the Execute Method 242Overriding a Default Connection with ObjectContext.Connection 242Handling Command Execution with EntityClient 244

Merging Results into the Cache with MergeOptions 247

Attaching and Detaching Objects from the ObjectContext 253

ObjectStateEntry State Methods for Managing State 258

Data Validation with the SavingChanges Event 261

Trang 11

Summary 266

11 Customizing Entities 267

The On[Property]Changed and On[Property]Changing Methods 271Using PropertyChanged to Calculate Database-Computed Columns

The ObjectContext.ObjectMaterialized Event 275

The EntityObject.PropertyChanging

and EntityObject.PropertyChanged Events 280

Creating Your Own Partial Methods and Properties 284

Using Partial Classes for More Than Just Overriding Methods

Customizing a Template for Major Class Modifications 295Switching Between the Default Template and a Custom Template 295

12 Data Binding with RAD ASP.NET Applications 297

Using the EntityDataSource Control to Access Flat Data 298

Creating a GridView and an EntityDataSource Concurrently 299Configuring an EntityDataSource with Its Wizard 299

Understanding How the EntityDataSource Retrieves and Updates

Trang 12

Accessing Foreign Keys When There Is No Foreign Key Property 308Working with Related EntityReference Data 309Using EntityDataSource.Include to Get Related Data 309Displaying Data That Comes from EntityReference

Using a New EntityDataSource Control to Enable Editing

of EntityReference Navigation Properties 312Editing EntityReferences That Cannot Be Satisfied

Binding an EntityDataSource to Another Control

Editing Related Data Concurrently with Multiple

Working with Hierarchical Data in a Master/Detail Form 317

Specifying Your Own Entity SQL Query Expression

Using a New EntityDataSource to Add a Third Level of Hierarchical

Using the EntityDataSource.Inserting Event to Help with Newly

13 Creating and Using POCO Entities 335

Creating an ObjectContext Class to Manage the POCOs 339

Understanding the Importance of DetectChanges 341

Exploring and Correcting POCOs’ Impact on Two-Way Relationships 342Using the DetectChanges Method to Fix Relationships 343Enabling Classes to Fix Their Own Relationships 344

Trang 13

Using Proxies to Enable Change Notification, Lazy Loading,

Creating a Model That Works with Preexisting Classes 358Code First: Using Entity Framework with No Model at All 359

14 Customizing Entity Data Models Using the EDM Designer 361

Mapping Table per Type Inheritance for Tables That Describe

Specifying or Excluding Derived Types in Queries 368Creating New Derived Entities When the Base Entity Already Exists 370

Querying, Editing, and Saving a Split Entity 378Mapping Stored Procedures to Split Tables and More 380Splitting a Single Table into Multiple Entities 381Filtering Entities with Conditional Mapping 383Creating a Conditional Mapping for the Activity Entity 385Querying, Inserting, and Saving with Conditional Mappings 385

Removing the Conditional Mapping from Activity and Re-creating

Implementing Table per Hierarchy Inheritance for Tables That Contain

Setting a Default (Computed) Value on the Table Schema 391

Choosing to Turn a Base Class into an Abstract Class 393Creating Complex Types to Encapsulate Sets of Properties 393

Trang 14

Querying, Creating, and Saving Entities That Contain Complex Types 397Removing the Complex Types from the Model 398

15 Defining EDM Mappings That Are Not Supported by the Designer 403

Using Model-Defined Functions to Return More Complex Results 407

Reading the Results from a Complex Function 408Mapping Table per Concrete (TPC) Type Inheritance for Tables

Using QueryView to Create Read-Only Entities and Other Specialized

Finding a Common Use Case for QueryView 413

Creating a QueryView Mapping for CustomerNameAndID 414

16 Gaining Additional Stored Procedure and View Support in the Raw XML 419

Reviewing Procedures, Views, and UDFs in the EDM 419Working with Stored Procedures That Return Data 420Using Functions That Match an Entity Whose Property Names Have

Query Stored Procedures and Inherited Types 421

Replacing Stored Procedures with Views for Composability 423Queries That Return Multiple Result Sets 424Executing Queries on Demand with ExecuteStoreQuery 424Querying to a Class That Is Not an Entity 424

Defining a Complex Type in the Model Browser 427

Using DefiningQuery to Create Your Own Views 431

Trang 15

Creating Associations with the New Entity 437Using DefiningQuery to Solve More Complex Problems 438

Executing SQL on the Fly with ExecuteStoreCommand 440Using Functions to Manipulate Data in the Database 441Mapping Insert/Update/Delete to Types Within an Inheritance Structure 444What If Stored Procedures Affect Multiple Entities in an Inheritance

Implementing and Querying with User-Defined Functions (UDFs) 445

17 Using EntityObjects in WCF Services 449

Planning for an Entity Framework–Agnostic Client 450Assessing the Pros and Cons of an Entity Framework–Agnostic

Building a Simple WCF Service with EntityObjects 452

Client Rules for Identifying Changes in an EntityCollection 463

Building a Simple Console App to Consume an EntityObject Service 467Enabling the Client Application to Receive Large Messages

Creating Methods to Test the Service Operations 469Analyzing the GetAndUpdateCustomer Method 473Testing Out the Other Service Operations 474

Putting WCF Data Services in Perspective 475

Filtering at the Service Level Using QueryInterceptor 480

Exposing Related Data Through the Service 481Preparing for WCF Data Services’ Limitations 483

Learning More About Creating and Consuming WCF Data Services 485

Trang 16

Understanding How WCF RIA Services Relates to the Entity Framework 485

18 Using POCOs and Self-Tracking Entities in WCF Services 489

Updating the POCO Classes Based on the Current BreakAway Model 490Isolating the POCO Entities in Their Own Project 491Adding Custom Logic to the POCO Entities with a Base Class 493

Preventing Properties from Being Marked As Virtual 496Building a WCF Service That Uses POCO Classes 497

Using the Self-Tracking Entities Template for WCF Services 503Creating and Exploring the Self-Tracking Entities 503Putting the Change-Tracking Logic Where It’s Needed 505Creating a WCF Service That Uses Self-Tracking Entities 506Watching Self-Tracking Entities Under the Covers 507Inspecting the Generated Context Class and Extensions 513Using POCO Entities with WCF Data and RIA Services 515

Using POCO Entities in WCF RIA Services 517Sorting Out the Many Options for Creating Services 519

19 Working with Relationships and Associations 521

Deconstructing Relationships in the Entity Data Model 522Understanding How the Entity Data Model Wizard Creates

Understanding Additional Relationship Items 525Handling Nonessential Navigation Properties 526Understanding the Major Differences Between Foreign Key Associations

Deconstructing Relationships Between Instantiated Entities 529Understanding Relationship Manager and the IRelatedEnd Interface 530

Taking a Peek Under the Covers: How Entity Framework

Understanding Referential Integrity and Constraints 537Implementing Deletes and Cascading Deletes 540

Trang 17

Defining Relationships Between Entities 542The CLR Way: Setting a Navigation Property to an Entity 543

Setting an EntityReference Using an EntityKey 544Loading, Adding, and Attaching Navigation Properties 545

EntityReference.Load and EntityCollection.Load 547Loading from Detached Entities: Lazy and Explicit 547

Learning a Few Last Tricks to Make You a Relationship Pro 551Using CreateSourceQuery to Enhance Deferred Loading 551Getting a Foreign Key Value in an Independent Association 552

20 Real World Apps: Connections, Transactions, Performance, and More 555

Working with Connection Strings Programmatically 557

Getting the Store Connection from EntityConnection 562

Understanding Implicit Entity Framework Transactions 565Specifying Your Own Read/Write Transactions 566Specifying Your Own Read-Only Transactions 569

Precompiling LINQ to Entities Queries for Performance 585

Trang 18

Forcing an ObjectContext to Use Its Own Thread 591Implementing Concurrent Thread Processing 593

21 Manipulating Entities with ObjectStateManager and MetadataWorkspace 597

Manipulating Entities and Their State with ObjectStateManager 598Refreshing Your High-Level Understanding of ObjectStateEntry 599Getting an ObjectStateManager and Its Entries 599Building Extension Methods to Overload GetObjectStateEntries 600Building a Method to Return Managed Entities 602Using GetObjectStateEntry and TryGetObjectStateEntry 603Mining Entity Details from ObjectStateEntry 604Leveraging the ObjectStateManager During Saves 609Using ObjectStateManager to Build an EntityState Visualizer 611Retrieving an ObjectStateEntry Using an EntityKey 612Reading the OriginalValues and CurrentValues of an

Determining Whether a Property Has Been Modified 614

Getting ComplexType Properties Out of ObjectStateEntry 615Modifying Values with ObjectStateManager 619Working with Relationships in ObjectStateManager 620

Clearing the MetadataWorkspace from Memory 623Understanding the MetadataWorkspace ItemCollections 624Retrieving Metadata from the MetadataWorkspace 625Querying the Metadata with LINQ to Objects 628Building Dynamic Queries and Reading Results 629Building Entity SQL Queries Dynamically Using Metadata 629Creating Queries on the Fly with CreateObjectSet and Query

Reading the Results of a Dynamically Created Query 634Creating and Manipulating Entities Dynamically 637Creating EntityObjects Without Entity Classes 637Creating Entities and Graphs Dynamically 640

22 Handling Exceptions 645

Handling EntityConnectionString Exceptions 647

Trang 19

Connection String Can’t Be Found or Is Improperly Configured:

Metadata Files Cannot Be Found: System.Data.MetadataException 648

Invalid LINQ to Entities Query Expressions:

UpdateException: Thrown by Broken Constraints in the Database 655Relying on Entity Framework to Automatically Roll Back When an

Planning for Other Exceptions Related to the Entity Framework 657

23 Planning for Concurrency Problems 659

Understanding Database Concurrency Conflicts 660Understanding Optimistic Concurrency Options in the Entity Frame-

Forcing the User’s Data to the Server (ClientWins) 661Refreshing the User’s Data with Server Data (StoreWins) 661

Using rowversion (a.k.a timestamp) for Concurrency Checks 662Implementing Optimistic Concurrency with the Entity Framework 663Flagging a Property for Concurrency Checking 664How the Entity Framework Uses the ConcurrencyMode Property 665Concurrency Checking Without a rowversion Field 666Concurrency Checking on a Checksum in the Data Store 666Concurrency Checks for EntityReference Navigation Properties 667

Concurrency Checks and Stored Procedures 668

Trang 20

Refreshing Collections of Entities 673

Rewinding and Starting Again, and Maybe Again After That 676

Handling Concurrency Exceptions at a Lower Level 678Handling Exceptions in a Granular Way Without User Intervention 678

Handling Exceptions When Transactions Are Your Own 682

24 Building Persistent Ignorant, Testable Applications 685

Testing the BreakAway Application Components 686

Writing an Integration Test That Hits the Database 687

Writing a Unit Test That Focuses on Custom Logic 689

Starting with the Model and Its POCO Entities 697Building an Interface to Represent a Context 698Modifying the BAEntities ObjectContext Class to Implement

Creating the IEntityRepository Interface 702

Testing GetReservationsForCustomer Against the Database 706

Building Tests That Do Not Hit the Database 714Adding Validation Logic to the POCO Class 714

Providing ManagedEntities in the FakeContext 716Hiding the Context from the Lower Layers with Unit of Work 718Testing UnitOfWork Against the Database 720

Leveraging Precompiled Queries in Your Repositories 722Using the New Infrastructure in Your Application 723Adding a UI Layer That Calls the Repository 723Application Architecture Benefits from Designing Testable Code 724

Trang 21

25 Domain-Centric Modeling 727

Creating a Model and Database Using Model First 728Creating a Conceptual Model in the Designer 728

Creating Association and Inheritance Hierarchies 734Generating Database Schema from the Model 738

Testing the Code-First Application and Database 753

Using M Metadata in Entity Framework Applications 758

26 Using Entities in Layered Client-Side Applications 761

Moving Other ObjectContext-Dependent Logic to the DataBridge 768Ensuring That Lazy Loading Doesn’t Negatively Impact the Layered

27 Building Layered Web Applications 783

Understanding How ObjectContext Fits into the Web Page

Return Results, Not Queries, from the DataBridge Class 785

Exploring Options for Updating Entities in an ASP.NET Web Forms

Comparing ASP.NET’s State Solutions to the Needs of the Entity

Trang 22

Building an Entity Manager to Act As a DataBridge 795Retrieving Data for Display and for Future Updates 797Making the Related Data Accessible to the Client 799Getting Data from the Manager to the Client 800Adding Lists for User Selection Controls 803

Replacing the Context with Repositories 813Editing Entities and Graphs on an MVC Application 814

Interacting with the ReservationController 817

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

Trang 23

I first met Julie Lerman (rhymes with “German”) while she was visiting the Microsoftcampus for a Software Design Review (SDR) An SDR is an event where we invitecustomers 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 nologies 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

tech-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 secondedition of her famous EF book And by “researching,” I mean “pointing out our mis-takes.” 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 rethinkwhat 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 wellrespected because of her first EF book that anything she said received extra attentionfrom the EF team in ways I don’t see for many senior architects, let alone lowly programmanagers 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 2010TechEd in New Orleans, I had the privilege of being Julie’s “code monkey,” whichmeant mostly that I fetched her coffee, carried her bags, and wrote her code while sheentertained and educated a packed room In 60 minutes, she did a tour de force tourthrough nearly all the new features in EF 4.0, driving me through one complete demoevery 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’srapt attention

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

Trang 24

During her presentation, Julie fielded questions on all manner of EF details and relatedtopics, but the one that made me cringe under the weight of history is the one I alwaysget, too: “Why should we use EF when Microsoft has already given us so many otherdata access technologies?” Julie’s answer came without hesitation: “Because it’s thebest!”

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 thatbest fits your specific business problem I can also say that the Entity Framework isthe 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 meetsmost 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

Trang 25

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 atTech Ed, I happily crossed the lovely bridge between the Convention Center and thehotel where the meeting was to take place

Little did I know I was about to see a new technology from Microsoft’s Data grammability team that was going to be the focus of my attention for the next few years

Pro-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 wascoming in the next version of ADO.NET It would allow developers to create their ownviews 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 withdata looked to me, I had to put it in a back corner of my mind and let it simmer for afew months I finally downloaded the preview and began playing with it What wasmost fun to me when I started exploring this technology, called Entity Framework, wasthe lack of serious documentation, which forced me to play with all of its knobs anddials 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

bor-ing) 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 derlying Entity Data Model are to Microsoft They are a critical part of Microsoft’sstrategy for the data access that all of its products perform, whether this is the data thatReporting 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

Trang 26

un-As the Entity Framework evolved and further CTPs were released, followed by betas,

I became quite fond of working against a data model and no longer having to thinkabout the structure of the database I was working against I began to peel away the toplayers of the Entity Framework and discovered that I could make it do nearly anything

I wanted as I gained a better understanding of how it worked When I hit a wall, I askedthe Entity Framework team how to get past it, and if there wasn’t a way to do so, Icamped out on their virtual doorstep until they modified the framework or Designer

to enable me to do what I wanted and what I knew other developers would need.During this time, I was excited to share what I was learning with other developersthrough the MSDN forums, my blog, conference sessions, and articles However, Iconstantly felt restrained by the time or space allotted to me Conference sessions aregenerally 75–90 minutes long Magazine articles tend to be 5–10 pages I felt as though

I was going to self-combust if I couldn’t share all of this new information, and so Icontacted O’Reilly to ask whether I could write a book about the Entity Framework

My editor on the first edition, John Osborn, was a bit taken aback because for years Ihad shunned publishers, saying I would have to have lost my mind to write a book It’snot a simple undertaking But I knew that if I didn’t write a book about ADO.NETEntity Framework, I certainly would lose my mind The time had come I was so excited,and of course, I had no idea what I was in for!

I spent almost a year writing the book that ended up at a little over 800 pages and morethan two pounds on the scale When the book was released in February 2009, Microsoftwas already well underway on the next version of Entity Framework, which was goingthrough major changes After spending some time with the early releases of what was

to become Entity Framework 4, and with some trepidation, I finally decided to revisethe book This was after having enlisted many friends to “please, just shoot me” if Iever talked about writing another book Thankfully, nobody took me up on the request.They admitted it was because they wanted a new version of my book targeted at thenew version of Entity Framework

Once again, I had no idea what I was in for This edition has been much more than arevision I have had to rethink every sentence in the book, throw out entire chapters,add new chapters, rethink and rewrite most of the code samples, and of course, learnabout a slew of major features that have been added to Entity Framework I spent overnine months of constant effort writing this new edition, and now here it is

Who This Book Is For

This book is written for developers who are familiar with NET programming, whetherthey are entirely new to the Entity Framework or have been using it and want to solidifytheir current understanding as well as go deeper Throughout the book, I highlightnotable changes for developers who have been using the first version of Entity Frame-work The first half of the book (Chapters 1 12) covers introductory topics, and thelatter half (Chapters 13–27) dives under the covers to give you a deep understanding

Trang 27

of what you’ll find in the Entity Framework and how it works, as well as how to getthe most out of it.

The early walkthroughs, which demonstrate the use of the Entity Framework in a riety of applications (Windows Forms, Windows Presentation Foundation, ASP.NET,WCF services, and WCF Data Services), are written so that you can follow them even

va-if you have never created a particular application type before

The goal of this book is to help developers not only get up and running with the EntityFramework, but also be empowered to gain granular control over the model and theobjects that result through use of the core Entity Framework APIs This second editionfocuses on the version of Entity Framework in Visual Studio 2010 and NET 4.Although the book will provide some guidance for using the Entity Framework in yourapplication architecture, it is not a book about architecture Instead, the book attempts

to provide you with the information and knowledge you need to use the Entity work to solve your specific domain problems

Frame-Because of the vast scope of the Entity Framework, many topics on tools that leveragethe Entity Framework, such as WCF RIA Services (a.k.a Astoria) and SQL Modeling,are touched on but not covered in depth

Some of the Entity Framework’s features are comparable to LINQ to SQL and otherobject relational models such as NHibernate and LLBLGen Pro Apart from a fewparagraphs in Chapter 1, this book does not directly position the Entity Frameworkagainst these object relational models

All of the code samples in Programming Entity Framework, Second

Ed-ition, are provided in C# Where there are significant syntax differences,

Visual Basic is included as well.

How This Book Is Organized

Programming Entity Framework, Second Edition, focuses on two ways for you to learn.

If you learn best by example, you’ll find many walkthroughs and code samples out the book; if you’re always looking for the big picture, you’ll also find chapters thatdive deep into conceptual information I have tried to balance the walkthroughs andconceptual information I provide so that you will never get too much of one at a time.The first half of the book is introductory, and the second half digs much deeper Fol-lowing is a brief description of each chapter:

through-Chapter 1, Introducing the ADO.NET Entity Framework

This chapter provides an overview of the ADO.NET Entity Framework—where itcame from, what problems it attempts to solve, and the classic “10,000-foot view”

of what it looks like The chapter also addresses the most frequently asked

Trang 28

questions about the Entity Framework, such as how it fits into the NET work, what databases it works with, what types of applications you can write with

Frame-it, how it differs from object relational models, and how it works with the rest ofADO.NET

Chapter 2, Exploring the Entity Data Model

The Entity Data Model (EDM) lies at the core of the Entity Framework This ter explains what the EDM is, and teaches you how to create one using the EDMWizard and then manipulate your model using the Designer You will also get awalkthrough of the various parts of the EDM, viewing it through the Designer orthrough its raw XML

chap-Chapter 3, Querying Entity Data Models

The Entity Framework provides a number of methods for querying against theEDM—LINQ to Entities, Entity SQL with ObjectQuery, EntityClient, and a fewmore Each method has its own benefits In this chapter, you will learn the basicsfor leveraging the various query modes by requesting the same data using eachmechanism You will also learn the pros and cons for choosing one method overanother, as well as gain an understanding of what happens behind the scenes inbetween query execution and the creation of objects from the data that results

Chapter 4, Exploring LINQ to Entities in Greater Depth

With the query basics in hand, you can now learn how to perform different types

of tricks with querying: projection, filtering, aggregates, and so forth Because theobjects you are querying are related, you can also query across these relationships.This chapter will walk you through a great variety of queries focusing on LINQ toEntities This is by no means an exhaustive depiction of every type of query youcan perform, but it will give you a huge head start

Chapter 5, Exploring Entity SQL in Greater Depth

This chapter revisits the LINQ to Entities queries from Chapter 4 and shows how

to express the same types of queries using Entity SQL You’ll also learn some cific tips about working with Entity SQL in this chapter

spe-Chapter 6, Modifying Entities and Saving Changes

This chapter presents a high-level view of how the Entity Framework trackschanges to entities, processes updates, and builds the final queries that are executed

at the database By having a better understanding of the Entity Framework’s defaultfunctionality, you will be better prepared to address common concerns regardingsecurity and performance Additionally, understanding the default process willmake the following chapter on stored procedures much more meaningful

Chapter 7, Using Stored Procedures with the EDM

This chapter is the first of two to dig into using stored procedures in the EntityFramework The EDM Designer provides support for one set of scenarios, and that

is what is covered in this chapter Chapter 16 covers the set of scenarios that requiremore effort

Trang 29

Chapter 8, Implementing a More Real-World Model

Up to this point in the book, you will have been working with a very simplisticdatabase and model so that you can focus on all of the new tools This chapterintroduces a larger model and database that support the fictitious travel adventurecompany BreakAway Geek Adventures and which you will use throughout the rest

of the book With this model, you will get a better understanding of building andcustomizing a model Chapters 14 and 15 will go even further into customizing themodel with advanced modeling and mappings

Chapter 9, Data Binding with Windows Forms and WPF Applications

This chapter provides two walkthroughs for using the Entity Framework to form data binding in Windows Forms and Windows Presentation Foundation(WPF) In the course of these walkthroughs, you’ll learn a lot of tips and tricks thatare specific to doing data binding with Entity Framework objects, as well as expandyour knowledge of the Entity Framework along the way

per-Chapter 10, Working with Object Services

The Entity Framework’s Object Services API provides all of the functionality hind working with the objects that are realized from the data shaped by your EntityData Model Although the most critical of Object Services’ features is its ability tokeep track of changes to entity objects and manage relationships between them, itoffers many additional features as well This chapter provides an overview of all ofObject Services’ responsibilities, how it impacts most of the work you do with theEntity Framework, and how you can use these features directly to impact how theEntity Framework operates Later chapters focus even more deeply on particularareas within Object Services

be-Chapter 11, Customizing Entities

So far, the objects you will have been working with are based on the default classesthat the Entity Framework generates directly from the model, but you don’t need

to be limited to what’s in the objects There are plenty of opportunities for tomizing the code-generated classes This chapter walks you through how to takeadvantage of these extensibility points It is also possible to completely avoid thegenerated classes and use your own custom classes, an option we will cover in

cus-Chapter 13

Chapter 12, Data Binding with RAD ASP.NET Applications

It’s time to create another application with the Entity Framework There are a lot

of hurdles to overcome when using the Entity Framework in an ASP.NET cation that allows users to edit data The EntityDataSource control is part of thefamily of ASP.NET DataSource controls that you can configure in the UI and thatwill automate data access and updating for you This chapter will show you how

appli-to use this control You’ll also get a chance appli-to use ASP.NET Dynamic Data Controls

in this chapter Later chapters will teach you what you need to know to overcomethese hurdles yourself, and Chapter 27 leverages this knowledge to address build-ing layered ASP.NET applications rather than putting the logic in the UI

Trang 30

Chapter 13, Creating and Using POCO Entities

A critical advancement to Entity Framework in NET 4 is its support for Plain OldCLR Objects (POCOs) The POCO support means that entity classes are notrequired to inherit from Entity Framework’s EntityObject class Building POCOsopens the door for a more agile architecture, unit testing, repositories, and persis-tence ignorance, all while continuing to benefit from the Entity Framework Thischapter provides an introduction to Entity Framework’s POCO support Laterchapters will leverage POCOs to show alternative patterns, build repositories andtests, and consume the POCOs in a variety of application types

Chapter 14, Customizing Entity Data Models Using the EDM Designer

One of the most important features of the Entity Data Model is the ability to tomize it to shape your data structure in a way that is more useful than workingdirectly against the database schema This chapter walks through many of the waysyou can achieve this with the Designer, demonstrating how to implement a variety

cus-of inheritance mappings, create an entity that maps to multiple tables, build plex types, and more If you are following along with the walkthroughs, most ofthe modifications you make to the sample model in this chapter you will use forapplications you’ll build in later chapters

com-Chapter 15, Defining EDM Mappings That Are Not Supported by the Designer

The Entity Framework model supports even more ways to map back to the base but, unfortunately, not all are supported by the Designer In this chapter,you’ll learn about the most common types of mappings that you might want to usebut will have to open up the raw XML to implement Among these are

data-DefiningQuery, QueryView, and even nonexistent database views and stored dures that you can define directly in the Entity Framework metadata

proce-Chapter 16, Gaining Additional Stored Procedure and View Support in the Raw XML

Chapter 7 covers the stored procedure scenarios that the Designer supports, butyou can achieve much more if you are willing to crack open the model’s raw XMLand perform additional customizations This chapter will walk you through adding

“virtual” store queries and stored procedures into the model, and taking advantage

of other features that will make the model work for you, rather than being strained by the Designer

con-Chapter 17, Using EntityObjects in WCF Services

Like ASP.NET, using the Entity Framework in web and WCF services provides anumber of challenges In this chapter, you will learn how to build and consume aWCF service that interacts solely with EntityObjects If you have never createdservices before, have no fear The walkthroughs will help you with step-by-stepinstructions You will also create a WCF Data Service and get a quick look at WCFRIA Services This chapter is the first of two that address building services

Chapter 18, Using POCOs and Self-Tracking Entities in WCF Services

The new POCO support in Entity Framework 4 makes building WCF Services alot simpler This chapter enhances the POCO entities you built in Chapter 13 and

Trang 31

uses them in a revised implementation of the WCF Services you created in ter 17 You’ll also learn about some of the differences when building WCF DataServices and WCF RIA Services with POCOs.

Chap-The preceding chapters will have provided you with a solid base of understanding forworking with the Entity Framework Starting with Chapter 19, you will learn about theEntity Framework’s advanced topics:

Chapter 19, Working with Relationships and Associations

The Entity Data Model is based on Entity Relationship Modeling, which is aboutentities and relationships Relationships are a critical part of the model and howthe Entity Framework performs its functions To really understand and control theEntity Framework and avoid hurting your head when the relationships don’t be-have the way you might expect, you will benefit from a deep comprehension ofhow relationships work in the model and your Entity Framework code This chap-ter will provide you with that understanding

Chapter 20, Real World Apps: Connections, Transactions, Performance, and More

Up to this point, you have seen bits and pieces of code out of the context of world applications But how does the Entity Framework fit in with the everydayconcerns of software developers? This chapter will address some of the many ques-tions developers ask after learning the basics about the Entity Framework How

real-do you control connections? Is there any connection pooling? Are database callstransactional? What about security? How’s the performance?

Chapter 21, Manipulating Entities with ObjectStateManager and MetadataWorkspace

This is another chapter where you get to dig even further into the APIs to interactwith your objects in the same way that many of the internal functions do With thetwo classes featured in this chapter, you can write code to generically work withentities or raw data whether you want to create reusable code for your apps or writeutilities There are some hefty samples in this chapter

Chapter 22, Handling Exceptions

Hard as we try to write perfect code, things can still go wrong in our applications,which is why we need exception handling The Entity Framework provides a set

of its own exceptions to help you deal with the unique problems that may occurwhen working with entities—poorly written queries, entities that are missing re-quired related objects, or even a problem in the database

Chapter 23, Planning for Concurrency Problems

This chapter follows up what you learned about exception handling in ter 22 with details on a particular type of exception: the OptimisticConcurrencyEx ception In addition to typical coding problems, data access highlights anotherarena of issues regarding concurrency: when multiple people are editing and up-dating data The Entity Framework supports optimistic concurrency and uses thisexception to detect these problems The chapter will show you how to prepare forconcurrency issues and take advantage of this exception

Trang 32

Chap-Chapter 24, Building Persistent Ignorant, Testable Applications

Chapter 13 introduced you to Entity Framework’s POCO support Chapter 24

shows you where the POCO support really shines Here you’ll get a chance to use

a pattern that leverages POCO support You will create repositories and a Unit ofWork and build unit tests against your Entity Framework code You’ll get to usethe repository in some applications in later chapters

Chapter 25, Domain-Centric Modeling

You’ll find more new NET 4 and Visual Studio 2010 goodness in this chapter aswell as a look to the future You are no longer required to build database-firstmodels The EDM Designer in Visual Studio 2010 supports model-first design.Build your model in the Designer and then automatically create a database schemafrom the model In this chapter, you’ll learn a lot more about working with theDesigner This chapter also takes a look at two not-yet-released technologies: En-tity Framework’s code first and SQL Modeling’s “M.” Both of these technologieslet you use Entity Framework without depending on a physical XML-based model

At this point in the book, you will have learned quite a lot about how the Entity work functions and how to work with the objects and the model in a granular way Thefinal two chapters focus on challenges and solutions for using the Entity Framework

Frame-in enterprise applications The book concludes with three appendixes: one that serves

as a guide to the assemblies and namespaces of the Entity Framework, another thathighlights unexpected behaviors when data-binding complex types, and a third thatlooks more deeply into the XML of the model’s metadata

Chapter 26, Using Entities in Layered Client-Side Applications

The earlier client application walkthroughs (Windows Forms and WPF) focused

on simple architectures to get you started with data binding Most medium to largeapplications are not written in this way, but rather separate their logic and datalayers from the UI This chapter will look at some of the specific features you cantake advantage of and challenges you might face when architecting Windows andWPF applications to keep the data access and business logic out of the user inter-face The chapter focuses on a sample WPF application using the repositories from

Chapter 24

Chapter 27, Building Layered Web Applications

Chapter 12 focused on building RAD ASP.NET apps using the EntityDataSource

control to avoid some of the issues with change tracking across tiers in the EntityFramework Now that you have learned much more about working with entities,

it is time to address these challenges head-on and learn how you can build ASP.NETapplication layers This chapter begins by addressing the specific issues that theASP.NET Page life cycle poses for entities, and then walks through two solutionsthat leverage the repositories from Chapter 24 The first is an ASP.NET Web Formsapplication that is built without the support of data source controls The second

is an ASP.NET MVC application that focuses on keeping data access code out of

Trang 33

the controller The samples in this chapter provide a first step toward concepts thatwill help you architect applications to fit your own domain model.

Appendix A, Entity Framework Assemblies and Namespaces

This appendix is a guide to the physical files that are part of the Entity Frameworkand each namespace in the programming model

Appendix B, Data-Binding with Complex Types

In Chapter 14, you learn how to create complex types in the model Complex typeshave some interesting (and often unexpected) behavior in data-binding scenarios.This appendix will prepare you for what to expect

Appendix C, Additional Details About Entity Data Model Metadata

Chapter 2 goes into plenty of detail about the model’s metadata, but if you arehardcore and want to dig a little further into the raw XML, this appendix shouldsatisfy your cravings

What You Need to Use This Book

This book focuses on the release of Entity Framework that is part of Microsoft VisualStudio 2010 and NET 4 You can use any of the Visual Studio 2010 versions, fromExpress through Ultimate

Although the Entity Framework can work with many database providers, the

SqlClient provider is part of Visual Studio 2010, and therefore all of the samples hereare based on SQL Server You can use SQL Server Express or Standard, and althoughthe Entity Framework runtime will recognize versions 2000, 2005, and 2008, none ofthe design tools will not work with SQL Server 2000 This book was written againstSQL Server 2008 Standard

Following is a specific list of system requirements:

• Windows XP with SP2, Windows Server 2003, Windows Vista and SP1, or dows 7

Win-• Microsoft SQL Server 2005, Microsoft SQL Server 2005 Express Edition, MicrosoftSQL Server 2008, or Microsoft SQL Server 2008 Express Edition

• Microsoft Visual Studio 2010

Trang 34

This Book’s Website

Visit http://www.ProgrammingEntityFramework.com/ (also available at http://www LearnEntityFramework.com/) for downloads, errata, links to resources, and other in-formation In the Downloads area, you will find:

• Scripts for creating the sample databases used in this book

• The sample applications from the book I will do my best to provide Visual Basicversions of many of the book’s samples Note that there are also hundreds of smallcode samples in the book In general, you will not find these small examples re-plicated on the website, although I will provide some of them for varying reasons

Conventions Used in This Book

The following typographical conventions are used in this book:

or the output from commands

Constant width bold

Shows commands or other text that should be typed literally by the user

Constant width italic

Shows text that should be replaced with user-supplied values

This icon signifies a tip, suggestion, or general note.

This icon indicates a warning or caution.

This icon indicates a Visual Basic code sample

This icon indicates a C# code sample

Trang 35

Using Code Examples

This book is here to help you get your job done In general, you may use the code inthis book in your programs and documentation You do not need to contact us forpermission unless you’re reproducing a significant portion of the code For example,writing a program that uses several chunks of code from this book does not require

permission Selling or distributing a CD-ROM of examples from O’Reilly books does

require permission Answering a question by citing this book and quoting examplecode does not require permission Incorporating a significant amount of example code

from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution An attribution usually includes the title,

author, publisher, and ISBN For example: “Programming Entity Framework, Second

Edition, by Julia Lerman Copyright 2010 Julia Lerman, 978-0-596-80726-9.”

If you feel your use of code examples falls outside fair use or the permission given here,feel free to contact us at permissions@oreilly.com

Safari® Books Online

Safari Books Online is an on-demand digital library that lets you easilysearch over 7,500 technology and creative reference books and videos tofind the answers you need quickly

With a subscription, you can read any page and watch any video from our library online.Read books on your cell phone and mobile devices Access new titles before they areavailable for print, and get exclusive access to manuscripts in development and postfeedback for the authors Copy and paste code samples, organize your favorites, down-load chapters, bookmark key sections, create notes, print out pages, and benefit fromtons of other time-saving features

O’Reilly Media has uploaded this book to the Safari Books Online service To have fulldigital access to this book and others on similar topics from O’Reilly and other pub-lishers, sign up for free at http://my.safaribooksonline.com

Comments and Questions

Please address comments and questions concerning this book to the publisher:O’Reilly Media, Inc

1005 Gravenstein Highway North

Sebastopol, CA 95472

800-998-9938 (in the United States or Canada)

707-829-0515 (international or local)

707-829-0104 (fax)

Trang 36

We have a web page for this book, where we list errata, examples, and any additionalinformation You can access this page at:

tech-First nods go to the technical reviewers These are the folks who were willing to readthe book in its roughest format and provide feedback to help me make it more usefuland comprehensible to you, the readers of the final version The award for helping tokeep me from exposing myself to humiliation over my nascent C# skills goes to WesleyBakker, a Dutch developer who does code reviews for a living I learned a lot from Wesand am grateful for his patience and kid-glove handling of my poor ego I also had anumber of EF and EF 4 newbies on board to help ensure that I didn’t make any leapswithout bringing them along You who are new to EF should thank them as well: CameyCombs, Suzanne Shushereba, Doug Holland, and John McConnell Ward Bell’s bril-liant architectural mind was displayed in comments that nearly exceeded my own text

He kept me honest and kept me thinking Everyone should email Ward and beg him

to write a book I don’t care what the topic is Ward has deep EF knowledge, as doesPer Okvist, whose feedback was also invaluable Two database gurus were enormouslyhelpful: Bob Beauchemin and Anil Das Their meticulous minds helped me in areasthat reached much further than discussions about database specifics

I also brought in some big guns to look at particular chapters in their area of expertise.Thanks so much to Greg Young, Bobby Johnson, Jarod Ferguson, and Mike Campbellfor helping me with my education in persistence ignorance and related topics and forlooking over the critical chapter on PI and testing to make sure that I had learned mylessons well I was close, but they helped guide me where I had strayed K Scott Alle-nand Imar Spaanjaars, both ASP.NET gurus, provided some additional guidance and

a read-through of a number of chapters

And then there was the real editing—the organization and flow of the text John born, who was the editor on the first edition of this book, was engaged to edit thisedition as well It’s hard for me to express my gratitude for the incredible dedication

Trang 37

Os-and expertise he provided Even though I thought myself much more experienced thistime around, John took every chapter and reorganized it, clarifying its focus and flow.

He is an incredible editor and I was very lucky to have him work on my book again.Along the way, of course, I had help from so many people at Microsoft on the EntityFramework team and beyond There is no way I can list them all, but here’s my bestshot (not in any special order): Danny Simmons, Elisa Flasko, Noam Ben-Ami, DiegoVega, Kati Iceva, Srikanth Mandadi, Alex James, Jarek Kowalski, Jeff Derstadt, RowanMiller, Craig Lee, David Annesley-DeWinter, Adi Unnithan, Andrew Peters, ShyamPather, and Tim Laverty Forgive me if I’ve neglected to mention someone

You’ll find that I have used (and recommended) a few additional tools throughout thebook The publishers generously provided me free licenses for which I’m grateful Therecommendations are because they are great tools, not because I didn’t have to pay forthem The tools include LINQPad, written by another O’Reilly author, Joseph Alba-hari; and ReSharper from JetBrains ReSharper was my first line of defense for ensuringthat my C# code wasn’t an embarrassment, while Wesley Bakker was my second Ilearned so much from both of them Entity Framework Profiler is an awesome tool forkeeping track of what’s going on in your database when using Entity Framework I alsoused two tools for producing images in this book The first is Snagit from TechSmith,which was completely invaluable for capturing and editing screenshots The second is

Balsamiq Mockups, which enabled me to have a little fun creating mock-ups of cation UIs in a number of chapters Finally, thanks to Red Gate, a great company withmany awesome tools For this book, I used its NET Reflector to inspect some assem-blies, and I’ve used their SQL Packager for creating a simple-to-install version of thesample databases for you to use

appli-My publisher has, as usual, provided great support for me I had not one, but twoeditors—this is not the job of editing the book, but of counseling me and holding myhand throughout the process Thanks to Laurel Ruma (who moved on to becomeO’Reilly’s über–Government 2.0 guru), and Mike Hendrickson who brings years ofexperience (not saying he’s old) for keeping me focused and helping me avoid beingtaken away in a funny white coat I was also lucky to have Audrey Doyle as my copyeditor again She did an amazing job on the first edition, so I begged O’Reilly to contracther again Lucky me, they did (She is going to hate that last nonsentence; I dare you

to leave it in, Audrey.)

If you read the Preface of my first book, you’ll be happy to know that this time around

I have no heart-wrenching pet losses to report, so you can put away the tissues you mayhave prepared yourself with In fact, we adopted a teenage Newfoundland dog namedSampson just as I began to write this edition Thank goodness for his needed afternoonwalks and his constantly entertaining personality, without which I’d have gone com-pletely mad during the time I have been writing this book You can meet this silly boy

on my blog at http://thedatafarm.com/blog/tags/Sampson

Trang 38

Somehow I have managed to retain my patient husband, Rich Flynn, to whom I ised “don’t worry, never again” when I finished the first edition He has just sufferedthrough another year of spaghetti, dirty dishes, ravaged potato chip supplies, and hav-ing to cede a little more space in bed as my waistline expanded thanks to my life in thecomputer chair (and all those potato chips).

prom-And finally, thanks to all of the incredible support that has come from the NET munity I’m very proud of the first edition of the book, and each private “thank you”

com-or complimentary public review on places like Amazon.com and your blogs has meant

so much to me This truly kept me going through what my Twitter followers know onlytoo well was an arduous process in writing this second edition

Oh, and to anyone who gave me chocolate…thanks!

Trang 39

Yes, it’s time.

Developers spend far too much of their precious time worrying about their backenddatabase, its tables and their relationships, the names and parameters of stored proce-dures and views, as well as the schema of the data that they return For NET developers,Microsoft’s new Entity Framework changes the game so that you no longer have to beconcerned with the details of the data store as you write applications You can focus

on the task of writing those applications, rather than accessing the data

The ADO.NET Entity Framework has shifted into becoming Microsoft’s core dataaccess platform for building NET applications It was released in July 2008 as part ofthe Visual Studio 2008 Service Pack 1 and NET 3.5 Service Pack 1, two years afterMicrosoft announced it at its TechEd 2006 Conference As a version 1 product, EntityFramework was greeted at first with skepticism, and its adoption was far from sweep-ing However, with the release of Visual Studio 2010 and NET 4 in April 2010, a muchimproved Entity Framework finally got the attention and excited responses of manydevelopers and NET teams, who are now quickly jumping aboard

Although ADO.NET retains its existing data access, as Microsoft’s core data accessstrategy going forward the Entity Framework will receive the bulk of the innovationand resources from the Business Platform Division (which owns all of the data pro-grammability tasks at Microsoft) It’s an important technology for Microsoft, and onethat you should not ignore Entity Framework is also being integrated into many ofMicrosoft’s products, whether the product uses Entity Framework to support its ownfeatures, such as with Commerce Server 2009’s Multi-Channel Commerce

Trang 40

Foundation,* or whether the product has support for interacting with the Entity work, such as with SQL Server Modeling.

Frame-Why do we need a new data access technology? After forcing developers to switch fromone data access technology to another—from DAO to RDO to ADO and then toADO.NET—with ADO.NET Microsoft seemed to have finally settled on a single tool

in which developers could invest With each release of Visual Studio and the NETFramework, ADO.NET has been enhanced and added to, but has remained backwardcompatible all along Our investment has been safe

And it remains safe, even though it will be stagnant The Entity Framework is anotherenhancement to ADO.NET, giving developers an added mechanism for accessing dataand working with the results in addition to DataReaders and DataSets

But Microsoft went as far as it could with the DataSet paradigm The next step was toenable developers to focus on a domain model while NET would automate the re-dundant tasks of database interaction

In this chapter, you will learn about the critical pieces of the Entity Framework, theEntity Data Model, entity classes, the core NET APIs, and Visual Studio design tools.You will also learn about how Entity Framework fits in with ADO.NET’s DataSets andLINQ to SQL Finally, you will learn about many of the changes and additions to EntityFramework in Visual Studio 2010 and NET 4, and how so many of the pain points inthe first version have been eliminated

The Entity Relationship Model: Programming Against a Model, Not the Database

A central benefit of the Entity Framework is that it frees you from being concerned withthe structure of your database All of your data access and storage is done against aconceptual data model that reflects your own business objects

With ADO.NET DataReaders and many other data access technologies, you spend a lot

of time writing code to get data from a database, read the results, pick out bits of datayou want, and push them into your business classes With the Entity Framework, you

no longer query against the schema of a database, but rather against a schema thatreflects your own business model As data is retrieved, you are not forced to reason outcolumns and rows and push them into objects, because they are returned as objects.When it’s time to save changes back to the database, you have to save only those objects.The Entity Framework does the necessary work of translating your objects back intothe rows and columns of the relational store The Entity Framework does this part ofthe job for you, similar to the way an Object Relational Mapping (ORM) tool works

* See http://msdn.microsoft.com/en-us/library/dd327929(v=CS.90).aspx.

Ngày đăng: 08/03/2014, 18:20

TỪ KHÓA LIÊN QUAN