Programming Entity Framework, 1st Edition - To Parent Directory

brawnywinderΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 11 μήνες)

1.408 εμφανίσεις

Table of Contents
Copyright .................................................................................................... 1
Introducing the ADO.NET Entity Framework ............................................. 1
Program against a model, not against the database ...................................................................................................................... 2
Entity Data Model: A Client Side Data Model ............................................................................................................................... 3
The Entity in Entity Framework .................................................................................................................................................... 6
Choose your back end .................................................................................................................................................................... 8
Entity Framework Features ......................................................................................................................................................... 10
Entity Framework in Web Services .............................................................................................................................................. 14
What about ADO.NET DataSets and LINQ to SQL? ................................................................................................................... 14
Entity Framework Pain Points ..................................................................................................................................................... 16
Programming Entity Framework ................................................................................................................................................. 18
Exploring the Entity Data Model ............................................................... 19
Why use an Entity Data Model? ................................................................................................................................................... 19
Entity Framework and the Entity Data Model ............................................................................................................................ 20
Your First Entity Data Model ...................................................................................................................................................... 20
The Entity Data Model in the Designer Window ........................................................................................................................ 23
Entity Properties .......................................................................................................................................................................... 25
The naked model: Inspecting the model's XML .......................................................................................................................... 28
A less daunting model view ......................................................................................................................................................... 28
The three parts of the model ........................................................................................................................................................ 29
CSDL: The Conceptual Schema .................................................................................................................................................... 31
SSDL – The Store Schema ........................................................................................................................................................... 43
MSL – The Mappings ................................................................................................................................................................... 48
Database Views in the Entity Data Model ................................................................................................................................... 52
From EDM to Classes: Code Generation ..................................................................................................................................... 53
Summary ...................................................................................................................................................................................... 53
Foundations of EDM Queries .................................................................... 54
Query the Model not the database ............................................................................................................................................... 54
Your first EDM query ................................................................................................................................................................... 55
LINQ to Entities ............................................................................................................................................................................ 61
Creating ObjectQueries Directly .................................................................................................................................................. 63
Method Based Syntax Queries for LINQ and Entity SQL ........................................................................................................... 67
The Shortest Entity SQL Query .................................................................................................................................................... 72
Combing LINQ Methods and Query Builder Methods ................................................................................................................ 72
EntityClient – the lowest level method for returning streamed data through EDM queries ..................................................... 73
Translation to Database queries ................................................................................................................................................... 77
Avoid Inadvertent Query Execution ............................................................................................................................................ 79
Chapter Summary ........................................................................................................................................................................ 80
More Querying the EDM .......................................................................... 80
Same Model, Friendlier Name ..................................................................................................................................................... 81
Projections in Queries .................................................................................................................................................................. 82
Projections in Entity SQL ............................................................................................................................................................ 88
Querying Across Associations ...................................................................................................................................................... 91
Joins and Nested Queries ........................................................................................................................................................... 102
Grouping ..................................................................................................................................................................................... 107
Shaped data returned by queries ................................................................................................................................................ 112
Deferred Loading and Eager Loading queries ............................................................................................................................ 117
Retrieving a single entity ............................................................................................................................................................ 124
Entity SQL's Wrapped & Unwrapped results ............................................................................................................................. 125
Summary .................................................................................................................................................................................... 130
Basics of Stored Procedures in the EDM ................................................. 130
Saving Entity Changes back to the database .............................................................................................................................. 130
Updating the model .................................................................................................................................................................... 131
The New Functions in the Model ............................................................................................................................................... 133
Implementing the Functions ...................................................................................................................................................... 136
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
What about the READ Stored Procedure? ................................................................................................................................. 142
The EDM Designer's Model Browser ......................................................................................................................................... 143
Map the last of the four functions — CustomersbyState. .......................................................................................................... 145
Chapter Summary ....................................................................................................................................................................... 147
Tuning up the Model ............................................................................... 147
The BreakAway Geek Adventures Business Model .................................................................................................................... 147
Create a Class Library Project to host an Entity Data Model .................................................................................................... 149
Inspect and clean up the new model .......................................................................................................................................... 151
Cleaning up the Navigation Property Names ............................................................................................................................. 153
Mapping a few Stored Procedures .............................................................................................................................................. 156
Many-to-Many Relationships .................................................................................................................................................... 160
Building the BreakAwayModel Project ...................................................................................................................................... 162
Chapter Summary ....................................................................................................................................................................... 166
Data Binding EF in Windows Apps: Part 1 ............................................... 166
Create a Windows Forms Application to use the BreakAway Model ........................................................................................ 167
Use WinForms DataSources to help with Data Binding ........................................................................................................... 169
Adding the Reservations Entity Collection to the form ............................................................................................................. 178
Editing Customers ...................................................................................................................................................................... 181
Editing the Navigation Properties (and trimming down the query) ......................................................................................... 183
Adding new Customers .............................................................................................................................................................. 188
Data binding with WPF Applications ......................................................................................................................................... 191
Create the new project ................................................................................................................................................................ 193
XAML's Role in Data binding ..................................................................................................................................................... 195
Selecting a Trip and Seeing its Details ....................................................................................................................................... 197
Adding the Activities EntityCollection to the mix ..................................................................................................................... 200
Editing Trips and their related data .......................................................................................................................................... 203
Adding Items to the Activities Entity Collection ....................................................................................................................... 205
The Last Task! Add new Trips to the Catalog ............................................................................................................................ 207
Chapter Summary ...................................................................................................................................................................... 210
Object Services ........................................................................................ 211
Where Do Object Services Fit into the Framework? .................................................................................................................. 211
Query Processing ........................................................................................................................................................................ 212
Object Materialization ............................................................................................................................................................... 224
Object Management ................................................................................................................................................................... 225
State Management and ObjectStateEntry .................................................................................................................................. 231
Relationship Management ......................................................................................................................................................... 234
Sending Changes Back to the Database ..................................................................................................................................... 240
Additional Features .................................................................................................................................................................... 245
Chapter Summary ...................................................................................................................................................................... 250
Customizing Entities .............................................................................. 250
Partial Classes in the Entity Framework .................................................................................................................................... 251
Partial Methods in Entity Framework ....................................................................................................................................... 252
Available Event Handlers ........................................................................................................................................................... 257
Other opportunities in Partial Classes ....................................................................................................................................... 264
Overload Context and Entity Methods ...................................................................................................................................... 267
Partial Classes are for more than just overriding existing methods and events ...................................................................... 269
Custom Code Generation ........................................................................................................................................................... 269
Create Common Methods or Properties for all Entities ............................................................................................................ 269
Chapter Summary ...................................................................................................................................................................... 270
ASP.NET EntityDataSource Control ....................................................... 270
The Entity Data Source Control ................................................................................................................................................. 271
Start with a Hello World Web App ............................................................................................................................................. 271
How the EntityDataSource creates a query ............................................................................................................................... 276
EntityDataSource and Related Data .......................................................................................................................................... 277
EntityDataSource and Database Hits ........................................................................................................................................ 284
EntityDataSource and Hierarchical Data .................................................................................................................................. 285
Understanding the EntityDataSource control ........................................................................................................................... 297
Summary .................................................................................................................................................................................... 302
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Advanced Entity Data Models ................................................................. 303
Entity Data Model and the EDM Designer ................................................................................................................................ 303
Inheritance in the EDM ............................................................................................................................................................. 304
Table per Type Inheritance (TPT) ............................................................................................................................................. 304
Entity Splitting ........................................................................................................................................................................... 318
Conditional Mapping ................................................................................................................................................................. 324
Table per Hierarchy Inheritance (TPH) .................................................................................................................................... 329
Complex Types ........................................................................................................................................................................... 335
QueryView for Read-Only Entities ............................................................................................................................................ 346
Additional Mapping Possibilities ............................................................................................................................................... 354
Chapter Summary ...................................................................................................................................................................... 355
Implementing Stored Procedures: Beyond the Basics ............................. 356
Are Stored Procedures Second Class Citizens in the Entity Framework? ................................................................................ 356
Does the Procedure Line up with an Entity? ............................................................................................................................. 357
Stored Procedures for Querying ................................................................................................................................................. 357
Adding Native Queries into the model ...................................................................................................................................... 364
Adding Native Views to the Model ............................................................................................................................................. 365
Commands that Affect the Persisted Database ......................................................................................................................... 376
Writing Queries against the functions ....................................................................................................................................... 381
Insert/Update/Delete mapping to Types within an Inheritance structure .............................................................................. 381
Chapter Summary ...................................................................................................................................................................... 382
Entities in Web and WCF Services .......................................................... 383
Building a Client that is Ignorant of the Entity Framework ..................................................................................................... 383
Building the ASMX Web Service and Client .............................................................................................................................. 385
The Client Application ................................................................................................................................................................ 397
Using Entity Framework with WCF Services ............................................................................................................................ 405
Summary .................................................................................................................................................................................... 434
Relationships and Associations .............................................................. 434
Associations in the EDM Designer ............................................................................................................................................ 435
How did the wizard create the association set? ......................................................................................................................... 436
Associations are only a piece of the Relationship puzzle .......................................................................................................... 438
The "Platinum Rule" about Object Graphs ................................................................................................................................ 439
Relationship Span ...................................................................................................................................................................... 440
Relationships are a two-way affair ............................................................................................................................................ 440
Relationships are First Class Citizens ........................................................................................................................................ 441
Navigation Properties in Entity Objects .................................................................................................................................... 444
Entity and EntityReference Properties ...................................................................................................................................... 445
EntityCollections ........................................................................................................................................................................ 447
Creating Relationships Between Entities .................................................................................................................................. 448
Moving an Entity to a new Graph .............................................................................................................................................. 458
iEnumerables & CreateSourceQuery to Enhance Deferred Loading ........................................................................................ 459
Getting a Foreign Key value ....................................................................................................................................................... 460
Associations Impact the Native Query ...................................................................................................................................... 462
Referential Integrity and Constraints ........................................................................................................................................ 463
Deletes and Cascading deletes ................................................................................................................................................... 466
Chapter Summary ...................................................................................................................................................................... 468
Making it Real: Connections, Transactions, Performance and more ...... 469
EntityConnection and Database Connections in the Entity Framework .................................................................................. 469
Entity Framework and Transactions ......................................................................................................................................... 477
Security ....................................................................................................................................................................................... 484
Performance ............................................................................................................................................................................... 488
Entities in Multi-Threaded Applications ................................................................................................................................... 503
Chapter Summary ...................................................................................................................................................................... 509
Take Control of Objects with ObjectStateManager and Metadata Workspace
................................................................................................................ 509
ObjectStateManager Manages ObjectStateEntries .................................................................................................................... 510
Getting an ObjectStateManager and its Entries ........................................................................................................................ 512
CurrentValues and OriginalValues ............................................................................................................................................. 517
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Building the ObjectStateEntry Visualizer .................................................................................................................................. 520
ObjectStateManager and SavingChanges .................................................................................................................................. 535
The MetadataWorkspace API .................................................................................................................................................... 538
Creating Entity Objects without Entity Classes ......................................................................................................................... 553
Combining Reflection, MetadataWorkspace and ObjectStateManager to dynamically create entities and build graphs ...... 556
Handling Entity Framework Exceptions ................................................. 560
General Exception Handling in .NET ........................................................................................................................................ 561
Preparing for Exceptions in Entity Framework code ................................................................................................................ 561
Problems caused by EntityConnectionString ............................................................................................................................ 563
Query Compilation Exceptions .................................................................................................................................................. 565
SaveChanges Command Execution Exceptions ........................................................................................................................ 568
ObjectStateEntries returned by Object Services Exceptions ..................................................................................................... 571
InvalidOperationExceptions ...................................................................................................................................................... 572
Problems caused when data is being concurrently edited by multiple parties ......................................................................... 573
Approaches to handling Concurrency conflicts ......................................................................................................................... 573
Optimistic Concurrency Options ............................................................................................................................................... 574
Setting up Optimistic Concurrency in Entity Framework ......................................................................................................... 577
Concurrency and EntityReference Navigation Properties ........................................................................................................ 581
Concurrency and Inherited Types .............................................................................................................................................. 581
Concurrency Checks and Stored procedures ............................................................................................................................. 582
Handling OptimisticConcurrencyExceptions ............................................................................................................................ 584
ObjectContext.Refresh ............................................................................................................................................................... 584
Low-Level Concurrency Exception Handling ............................................................................................................................ 596
Exceptions and Your Own Transactions ................................................................................................................................... 602
Chapter Summary ...................................................................................................................................................................... 604
Custom Classes in the Entity Framework ............................................... 605
Mapping Classes to the Entity Data Model ............................................................................................................................... 605
Implementing the IPOCO Interfaces ......................................................................................................................................... 615
Custom Class Assemblies and the Entity Data Model files ....................................................................................................... 622
Chapter Summary ...................................................................................................................................................................... 623
Considerations for using EF in Client Side Application Layers ............... 623
A Long Running ObjectContext ................................................................................................................................................. 625
New Ways to Perform Old Tricks .............................................................................................................................................. 625
Business Layer Class Primary Elements ................................................................................................................................... 628
A Master-Detail Data Entry Form ............................................................................................................................................. 629
The Customer List ...................................................................................................................................................................... 630
Returning a Customer Graph to the User Interface .................................................................................................................. 632
Supplying lists for the various drop downs ............................................................................................................................... 636
Generic Methods to return random entities .............................................................................................................................. 639
Saving Changes .......................................................................................................................................................................... 640
Rolling Back User Changes ........................................................................................................................................................ 642
Data binding in a Master Detail form and considerations for the business layer .................................................................... 646
Chapter Summary ...................................................................................................................................................................... 653
Considerations for implementing Layers in ASP.NET Applications ........ 654
Web Page Life Cycle ................................................................................................................................................................... 654
EntityObjects and Read-only web pages .................................................................................................................................... 657
Updating Entities in an ASP.NET Application .......................................................................................................................... 660
Evaluating ASP.NET's State Solutions against Entity Framework ........................................................................................... 661
ASP.NET's ObjectDataSource control ....................................................................................................................................... 665
The BreakAway Customer Management Web Page .................................................................................................................. 668
Using the Provider classes with the ObjectDataSources ........................................................................................................... 679
What about using Object Graphs in the Business Layer? ......................................................................................................... 687
Chapter Summary ...................................................................................................................................................................... 688
A Smarter WCF Service to Work with Entities ........................................ 689
Will your client agree to your data contract? ............................................................................................................................ 690
Recipe for a WCF Service that can update graphs ..................................................................................................................... 691
The Service Interface ................................................................................................................................................................. 698
Service Operation Implementation ........................................................................................................................................... 699
Implementing the Client ............................................................................................................................................................ 710
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Testing it all out with a simple Console App .............................................................................................................................. 717
Chapter Summary ....................................................................................................................................................................... 719
Entity Framework Today and Tomorrow ................................................ 720
What about Building Reports with Entity Framework? ............................................................................................................ 720
Extensions, Samples and Solutions from Microsoft .................................................................................................................. 722
Entity Framework v.Next ........................................................................................................................................................... 723
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Copyright
Copyright © Julia Lerman, 2009. All rights reserved.
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://safari.oreilly.com). For more
information, contact our corporate/institutional sales department: (800) 998-9938 or
corporate@oreilly.com.
Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered
trademarks of O'Reilly Media, Inc. The vulpine phalanger and related trade dress are
trademarks of O'Reilly Media, Inc.
Many of the designations uses 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.
While every precaution has been taken in the preparation of this book, the publisher and
authors assume no responsibility for errors or omissions, or for damages resulting from
the use of the information contained herein.
Chapter 1. Introducing the ADO.NET EntityFramework
Developers spend way too much time writing repetitive data access code and focusing on
the schema of their database. It's time to stop the madness.
The ADO.NET Entity Framework is a new Data Access platform from Microsoft for
writing .NET Applications. It was released in July 2008 as part of the Visual Studio Service
Pack 1 and .NET 3.5 Service Pack 1 package, two years after it was first announced at
Microsoft's TechEd 2006 Conference.
While the existing data access features remain in ADO.NET, this new framework is based
on Microsoft's core data access strategy going forward and therefore Entity Framework
will receive the bulk of the innovation and resources from Microsoft's Data
Programming Entity Framework, 1st Edition Page 1 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Licensed by
Dave Olsen
Programmability team. It's an important technology for Microsoft and therefore one that
you should not ignore.
Why do we need a new data access technology? After many years of forcing developers to
switch from DAO to RDO to ADO and then to ADO.NET, with ADO.NET it seemed that
Microsoft had finally settled on a tool that we could make a big investment in. As Visual
Studio and the .NET Framework have evolved, ADO.NET has evolved by enhancement
and addition but has remained backward compatible all along. Our investment was safe.
And it remains safe. Entity Framework is another enhancement to ADO.NET, giving
developers another mechanism for accessing data and working with the results in addition
to DataReaders and DataSets.
One of the core benefits of Entity Framework is that you don't have to be concerned with
the structure of your database. All of your data access and storage is done against a
conceptual data model that reflects your own business objects.
1.1. Program against a model, not against the database
With DataReaders and many other Data Access technologies the developer spends a lot of
time getting data from the database, reading through the results and picking out bits of
data and pushing them into your business classes. With the Entity Framework, you are
not querying against the schema of the database but against a schema which reflects our
own business model. As the data is retrieved, you are not forced to reason out the columns
and rows and push them into objects, they are returned as objects. When it's time to save
changes back to the database, you only have to save those objects. Entity Framework will
do the necessary work to translate your objects back into the rows and columns of the
relational store. Entity Framework does this part of the job for you, similar to the way an
Object Relational Mapping tool works.
Entity Framework uses a model called an Entity Data Model which evolved from Entity
Relationship Modeling, a concept that has been used in database development for many
years.
Entity Data Model's Roots
Entity Framework evolved from a methodology called Entity Relationship
Modeling (ERM) that has been trapped on whiteboards for over thirty years.
ERM defines a schema of entities and their relationships with one another.
Entities are not the same as objects. Entities define the schema of an object but
not its behavior. So it's something like the schema of a table in your database
except that it describes the schema of your business objects. We have drawn
Programming Entity Framework, 1st Edition Page 2 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
these ERMs for years to help us figure out how to transpose the structured
tabular data of our databases into the structure of our objects.
No mention of ERM is complete without a nod to Dr. Peter Chen who is credited
with the first definitive paper on Entity Relationship Modeling in 1976.
From Whiteboard to Bits and Bytes
With a host of database gurus in its ranks, Microsoft Research began devising
a way to automate the process of bridging a conceptual model to the database
schema. And it needed to be a two-way street so that we can retrieve data from
the database into our entities and persist changes back into the database.
In June 2006, Microsoft Research published its first paper on the Entity Data
Model, its answer to Entity Relationship Modeling. The paper's authors include
database legend, Jim Gray, who tragically disappeared while sailing off of the
coast of San Francisco Bay in 2007.
1.2. Entity Data Model: A Client Side Data Model
An EDM is a client side data model and it is the core of the Entity Framework. It is not the
same as the database model; that belongs to the database. The data model in the
application describes the structure of your business objects. It's as if you were given
permission to restructure the database tables and views in your enterprise's database so
that it the tables and relationships looked more like your business domain rather than the
normalized schema that is designed by database administrators.
Figure 1-1 shows the schema of a typical set of tables in a database. PersonDetails provides
additional information about a Person that the DBA has chosen to put into a separate table
for the sake of scalability. SalesPerson is a table that is used to provide additional
information for those people who are salespeople.
Figure 1-1. Schema of normalized database tables
Programming Entity Framework, 1st Edition Page 3 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
When working with this data from your application, your queries will be full of inner joins
and outer joins in order to access the additional data about Person records. Or you will
access a variety of pre-defined stored procedures and views which might each require a
different set of parameters and return data that is shaped in a variety of ways.
A TSQL query to retrieve a set of SalesPerson records along with their personal details
would look something like
SELECT SalesPerson.*, PersonalDetails.*, Person.*
FROM Person
INNER JOIN PersonalDetails
ON Person.PersonID = PersonalDetails.PersonID
INNER JOIN SalesPerson ON Person.PersonID = SalesPerson.PersonID
Imagine that a particular application could have its own view of what you wish the database
looked like. Figure 1-2 reshapes the schema.
Figure 1-2. Person data shaped to match your business objects.
Programming Entity Framework, 1st Edition Page 4 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
All of the fields from PersonDetails are now part of Person. And SalesPerson is doing
something that is not even possible in a database; it derives from Person, just as you would
in an object model.
Now imagine that you can write a LINQ query that looks like this:
from p in People.OfType<SalesPerson> select p
NOTE
LINQ only exists in C# and Visual Basic languages. With Entity Framework there
is another way to express queries which allows you not only to use other languages,
but provides additional benefits that you can take advantage as necessary. It's
called Entity SQL and you will learn much more about Entity SQL and LINQ to
Entities in Chapter 3 and Chapter 4.
In return you will have a set of SalesPerson objects with all of the properties defined by
this model.
Figure 1-3. The SalesPerson object
Programming Entity Framework, 1st Edition Page 5 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
This is the crux of how Entity Framework can remove the pain of having not only to interact
with the database, but having to translate the tabular data into objects.
1.3. The Entity in Entity Framework
The items described in the Entity Data Model are called entities. The objects that are
returned are based on these entities are Entity Objects. They differ from typical domain
objects in that they have properties but no behavior outside of methods to enable change
tracking.
Figure 1-4 shows the class diagram for both of the classes that get automatically generated
from the model. Each class as a factory method and methods that are used to notify the
Entity Framework if a property has changed.
Figure 1-4. Class Diagrams for the Person and SalesPerson entities
Programming Entity Framework, 1st Edition Page 6 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
You can add business logic to the generated classes, pull the results into you own business
objects or even link your business objects to the Entity Data Model and remove the
generated classes. But by definition, the entities only describe their schema.
In addition to being able to reshape the entities in the data model, you can define
relationships between entities. Figure 1-5 adds a Customer entity (also deriving from
person) and an Order entity to the model. Notice the relationship lines between
SalesPerson and Order, showing a One to Many relationship between them. There is also
a One to Many relationship between Customers and Orders.
Programming Entity Framework, 1st Edition Page 7 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Figure 1-5. SalesPerson and Customer entities each have a relationship to Order entities.
When you write queries against this version of the model, you don't need to use JOINS.
The model provides navigation between the entities.
This LINQ to Entities query retrieves Order information along with information about the
customer. It navigates into the Customer property of the Order to get the FirstName and
LastName of the Customer.
from o in context.Orders select
new {o.OrderID,o.OrderNumber,o.Customer.FirstName,o.Customer.LastName}
Once that data is in memory you can navigate through the objects and their properties,
myOrder.Customer.LastName, just as readily.
Entity Framework also lets you retrieve graphs which means that you can return shaped
data such as a Customer with all of its Orders already attached.
These are some of the huge benefits to querying against a data model rather than directly
against the database.
1.4. Choose your back end
You may have noticed that there has been no mention of the actual data store that owns
the data being queried. The model doesn't have any knowledge of the data store – what
type of database it even is much less what the schema is. And it doesn't need to.
The database you choose as your back end will have no impact on your model or your code.
Programming Entity Framework, 1st Edition Page 8 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Entity Framework communicates with the same ADO.NET Data providers that are already
used by ADO.NET; but with a caveat. The provider must be updated to support the Entity
Framework. The provider takes care of reshaping Entity Framework's queries and
commands into native queries and commands. All you need to do is identify the provider
and a database connection string so that Entity Framework can get to the database.
This means that if you need to write applications against a number of different databases,
you won't have to learn the ins and outs of each database. You can write queries with Entity
Framework's syntax (either LINQ to Entities or Entity SQL) and never have to worry about
the differences between the databases. If you need to take advantage of functions or
operators that are particular to a database, Entity SQL allows you to do that as well.
NOTE
You may notice the use of the term "data store" rather than always referring to the
database. While EF currently will be about working with databases, Microsoft's
vision is to work with any relational store, for example an XML file with a known
schema.
1.4.1. Available Providers
Microsoft's SqlClient API that is included with Visual Studio 2008 SP1 supports the Entity
Framework. It will allow you to use SQL Server 2000, 2005 and 2008. You can use the full
or Express versions of SQL Server 2005 and 2008 and the full version of SQL Server 2000.
SQL Server CE Version 3.5 supports EF as well in the System.Data.SqlServerCe.3.5 API.
At the time of writing this book there are already a host of other providers available and
more on their way that will allow you to use Oracle, IBM databases, SQLAnywhere, MySQL,
SQLite, VistaDB and many other databases. The providers are being written not only by
the database vendors but by third party vendors as well.
NOTE
On the resources page of the book's website, you can find a list of provider APIs
that support the Entity Framework.
Programming Entity Framework, 1st Edition Page 9 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
1.4.2. Access and ODBC
A provider that supports Entity Framework needs to have specific knowledge about the
type of database it is connecting to. It needs to be aware of the available functions and
operators for the database as well as the proper syntax for native queries ODBC providers
provide generic access to a variety of databases including Access and cannot furnish the
necessary database particulars to act as a provider for Entity Framework. Therefore ODBC
is not a valid provider for Entity Framework. Unless someone creates a provider
specifically for Access you won't be able to use it with Entity Framework applications.
Microsoft does not have plans to build an Access provider because the demand is too low.
1.5. Entity Framework Features
In addition to the Entity Data Model, Entity Framework provides a set of .NET APIs that
let you write .NET applications using the EDM. It also includes a set of design tools for
designing the model. Following is a list of Entity Framework's key features.
1.5.1. Entity Data Model
While the Entity Framework is designed to let you work directly with the classes from the
Entity Data Model, it still needs to interact with the database. The conceptual data model
described by the EDM is stored in an XML file whose schema identifies the Entities, their
properties. Behind the conceptual schema described in the Entity Data Model is another
pair of schema files that map your data model back to the database. One is an XML file
that describes your database and the other is a file that provides the mapping between your
conceptual model and the database.
During query execution and command execution (for updates), Entity Framework figures
out how to turn a query or command that is expressed in terms of the data model into one
that is expressed in terms of your database.
When data is returned from the database, it does the job of shaping the database results
into the entities and further materializing objects from those results.
1.5.2. Entity Data Model Design Tools
The screenshots in Figure 1-2 and Figure 1-3 are taken from the Entity Data Model
Designer. It is part of Visual Studio and provides you with a way to work visually with the
model rather than tangle with the XML. You will work with the designer right away in
Chapter 2 and learn how to use it to do some more advanced modeling, such as Inheritance,
in Chapter 11. You will also learn about the designer's limitations, such as the fact that it
does not support all of the features of the Entity Data Model. With some of the less
frequently used EDM features, you'll have to tangle with the XML after all. In Chapter 2
you will get a look at the XML and how it relates to what you see in the designer so that
Programming Entity Framework, 1st Edition Page 10 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
when it comes time to tangle in Chapter 11, you'll have some familiarity with the raw
schema files.
The designer also allows you to map stored procedures to entities which you'll learn about
in Chapter 5. Unfortunately the stored procedure support in the designer has its limitations
as well, so Chapter 11 will show you how to achieve what can't be done with the designer.
Another notable feature of the designer is that it will let you update the model from the
database to add additional database objects that you either did not need earlier or that
have been added to the database since you created the model.
1.5.2.1. The Entity Data Model Wizard
One of the EDM Design tools is the Entity Data Model Wizard. It allows you to point to an
existing database and create a model directly from the database so that you don't have to
start from scratch. Once you have this first pass at the model, you can begin customizing
the model in the designer.
This version of Entity Framework is much more focused on creating models from existing
databases. While it is possible to begin with an empty model, it's much more challenging
to create the model first and then wire it up to a database.
NOTE
There is no tool in the current version to create a database from the model, though
this is being targeted for the next version of Entity Framework which will be
released as part of the next version of Visual Studio (post Visual Studio 2008).
1.5.3. Managing Objects with Object Services
There are two main APIs in the Entity Framework. The one which you are likely to work
with most often is referred to as Object Services. Object Services sits on top of the Entity
Framework stack as shown in Figure 1-6 and provides all of functionality needed to work
with the objects that are based on your entities. Object Services provides a class called
EntityObject. Any class that inherits from EntityObject can be managed by Object Services.
This ranges from materializing objects from the results of queries against the EDM,
keeping track of changes to those objects, managing the relationships between the objects
and saving changes back to the database.
In between querying and updating, Object Services provides a host of capabilities to
interact with the entity objects such as automatically working with a lower level of Entity
Programming Entity Framework, 1st Edition Page 11 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Framework to do all of the work necessary to make calls to the database and deal with the
results. Object Services also provides the ability to serialize (both XML and binary).
Figure 1-6. Object Services sits on top of the Entity Framework stack
1.5.4. Change Tracking
Once an entity object has been instantiated, either as a result of data returned from a query
or by instantiating a new object in code, Object Services can keep track of that object. This
is the default for objects returned from queries. When Object Services manages an object
it can keep track of changes made to the object's properties or its relationships to other
entity objects.
Object Services then uses the change tracking information when it's time to update the
data. It constructs Insert, Update and Delete commands for each object that has been
added, modified or deleted by comparing the original values to the current values of the
entity. If you are using stored procedures in conjunction with the entities, it will pass the
current values (and any original values specifically identified) to those procedures.
Programming Entity Framework, 1st Edition Page 12 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
1.5.5. Relationship Management
Relationships are a critical piece of the Entity Data Model and in Object Services,
relationships are objects. If a SalesPerson has two Orders, there will be one relationship
object for his relationship with the first order and another object representing a
relationship between the SalesPerson and the second order.
This paradigm enables the Entity Framework to have a generic way of handling a wide
variety of modeling scenarios. But as you will find, especially in Chapter 16 which dives
deeply into relationships, this also requires that you have a very good understanding of
how these relationships work. Some of the rules of engagement when working with related
data are not very intuitive and you can write code that will raise plenty of exceptions if you
break these rules. Chapter 16 will provide plenty of insight into relationships in the Entity
Data Model so that you will be able to work with them expertly.
1.5.6. Databinding
Entity Objects can be used in many .NET databinding scenarios. In Windows Forms, you
can use entities as a data source for databound controls or as the data source for
BindingSource controls, which orchestrate the binding between objects and UI controls
on the form. Chapter 7 provides a well-informed walkthrough for using entities with a
BindingSource controls to edit and update data. Chapter 20 focuses on separating the data
access and other business logic from the user interface in order to provide better
architecture for your applications.
Chapter 7 also provides a walkthrough for databinding entities in Windows Presentation
Foundation (WPF) applications.
For ASP.NET, there is a new DataSource control called the EntityDataSource which works
in a similar way to the SqlDataSource and LinqDataSource controls, allowing you to
declaratively bind entity objects to your user interface. Chapter 10 is all about using the
EntityDataSource.
For layered applications, Chapter 21 focuses on pulling all of the data access out of the
ASP.NET user interface.
1.5.7. Entity Client
EntityClient is the other major API in Entity Framework. It provides the functionality
necessary for working the store queries and commands (in conjunction with the database
provider) connecting to the database, executing the command and retrieving the results
from the store and reshaping the results to match the Entity Data Model.
Programming Entity Framework, 1st Edition Page 13 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
You can work with EntityClient directly or work with Object Services. Object Services sits
on top of EntityClient. EntityClient is only able to perform queries and does so on behalf
of Object Services. The difference is that when you work directly with EntityClient, you
will get tabular results (though it can be shaped). If you are working with Object Services,
it will transform the tabular data created by EntityClient into Objects.
The tabular data returned by EntityClient is read only. Only with Object Services provides
change tracking and the ability to save changes back to the data store.
1.6. Entity Framework in Web Services
Entity Framework can be used anywhere that ADO.NET can be used including Web
Services and WCF Services. Chapter 13 walks through providing services for entities and
Chapter 21 revisits WCF Services using much of the knowledge you will gain in between
the two chapters.
At the same times that Entity Framework was released, another new technology called
ADO.NET Data Services (which you may know from its original code name, Astoria) was
also released. ADO.NET Data Services provides an automated way to expose data through
an Entity Data Model, a LINQ to SQL model or other particular interfaces, to allow wide
access to your data using HTTP commands such as GET and PUT. While this is a great
way to expose your data when you don't need to have a lot of control over control how it
is used, this topic won't be covered as part of this book. Here you will learn to write services
that are designed more specifically for an enterprise.
1.7. What about ADO.NET DataSets and LINQ to SQL?
Entity Framework is only part of the ADO.NET stack. DataSets and DataReaders are an
intrinsic part of ADO.NET and LINQ to SQL was part of the original release of Visual Studio
2008.
1.7.1. DataSets
DataSets and DataReaders are not going away. All of your existing investment will continue
to function and you can continue to use this methodology of retrieving data and interacting
with it. Entity Framework is a completely different way to retrieve and work with data. You
would not integrate the two technologies for example using Entity Framework to query
some data and then push it into a dataset. There would be no point. You should use one
or the other. As you learn about Entity Framework you will find that that it provides a very
different paradigm for accessing data. You may find that Entity Framework fits for some
projects but not others where you may want to stick with DataSets.
Programming Entity Framework, 1st Edition Page 14 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
Entity Framework uses DataReaders as well, the EntityDataReader which inherits the
same DbDataReader as SqlDataReader etc. This is what is returned by a query with
EntityClient. In fact, you'll find that the code querying the EDM with EntityClient looks
very similar to that which you use to query the database. It uses connections, commands,
command parameters and returns a DbDataReader that can be read the same way as the
others.
Some ADO.NET tools that are not available with Entity Framework are Query Notification
and ASP.NET's SQCacheDependency. Additionally the ADO.NET's SqlBulkCopy requires
a DataReader or DataSet to stream data into the database and therefore you cannot do
client side bulk loading with Entity Framework. Entity Framework does not have an
equivalent to ADO.ENT's DataAdapter.BatchUpdate. When Entity Framework saves
changes to the database, it can only send one command at a time.
There are a few things that are easier with DataSets than with Entity Framework such as
Unit Testing and change tracking across processes. You'll find a discussion of each of these
below.
1.7.2. LINQ to SQL
LINQ to SQL and Entity Framework look quite similar on the surface. They both provide
LINQ querying against a database using a data model.
Why both technologies? LINQ to SQL evolved from the LINQ project which came out of
folks working with language development. Entity Framework was a project of the Data
Programmability team and was focused on the Entity SQL language. By the time each
technology had come along far enough that it was being shown to other team at Microsoft,
it was clear that Microsoft had two great new technologies that could target different
scenarios. The Entity Framework team adapted LINQ to work with Entities which
confused developers even more because LINQ to Entities and LINQ to SQL look so much
alike.
LINQ to SQL eventually was brought into the Microsoft's Data Programmability team and
in November 2008 they announced that because the technologies target the same
problems, that going forward the team will focus on developing Entity Framework while
maintaining and tweaking LINQ to SQL. This is not a happy situation for many developers
who have made an investment in LINQ to SQL. While Microsoft has made no statements
about deprecating this great and fairly new tool, they have said they will provide a
migration path from LINQ to SQL to Entity Framework and will recommend Entity
Framework over LINQ to SQL.
Programming Entity Framework, 1st Edition Page 15 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
NOTE
At the time of writing, this is a fairly recent announcement about LINQ to SQL and
there's always the possibility that the outcome may change based on community
feedback.
The last chapter of this book will highlight some differences between Entity Framework
and LINQ to SQL that be more comprehensible once you have some knowledge about
Entity Framework.
1.8. Entity Framework Pain Points
This book is about Entity Framework Version 1 which was released in July 2008 as part
of Visual Studio 2008 Service Pack 1. Microsoft has a big vision for Entity Framework and
made an explicit choice to get as much as they could into the Visual Studio 2008 SP1
release. While it is an impressive technology with enormous flexibility, there is quite a lot
of functionality that is not surfaced in discoverable and easy to use ways. Additionally as
with any technology, there are features that some developers find impossible to live
without and will most likely wait until Version 2 to begin putting entity Framework into
production.
This book spends a lot of time looking into the depths of the APIs to show you how to get
around some of these limitations and attempts to point out potholes, hiccups and
omissions.
1.8.1. Entity Framework Designer
The Designer goes a long way to give you a visual to for working with the Entity Data Model
but not every capability of the EDM is easily achieved with the model and requires some
work in the raw XML. While most would agree that the features you need to code manually
are those which will be used less commonly, there are a few that stand out.
1.8.1.1. Stored Procedures
The designer supports a narrow use of stored procedures.
Using the designer, you can override Entity Framework's automatic generation of Insert,
Update and Delete commands by mapping an entity to a set of stored procedures with two
important rules. The first is that the stored procedure must line up with the entity. For
inserts and updates that means the values for the stored procedure parameters must come
from an entity's property. The second rule is that you have to override Insert, Update and
Delete or none at all, so you'll need to map all three functions.
Programming Entity Framework, 1st Edition Page 16 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
The designer supports read queries as long as the query results map directly to an entity.
If you have a query that returns random data, you will need to manually create an entity
for it to map to. That's not too hard in the designer, but there's another requirement which
will necessitate doing some work in the XML.
Chapter 5 walks through the scenarios that the designer supports easily and Chapter 12
digs down into the scenarios that will take more effort and walks you through the necessary
steps.
1.8.1.2. Unsupported EDM Types
The Entity Data Model has a very rich set of modeling capabilities demonstrated in Chapter
11. But the designer does not support all of the advanced modeling techniques, requiring
you to hand code them in the XML. In most cases, you can continue to work with the model
in the designer even though you won't see these particular model types, though you can
leverage them in your code. However there are a few model types, such as the very useful
ComplexType, that when included in the XML, will make it impossible to open the model
in the designer. The Designer is well aware of these limitations and at least provides an
alternate view that displays a message explaining why the model can't be opened. You'll
learn about this in Chapter 11.
1.8.1.3. Generate a database from the model
The Entity Data Model is based on a data driven design with the assumption that there is
an existing database for the model to map back to. This makes a lot of sense if you are
building an application for an existing database. Domain Driven Developers prefer to
create their object model first and have a database generated from that. The design tool
does not support this capability. It should appear in Version 2. In the meantime developers
in the community and at Microsoft are playing with a code generator called T4 _____
Templates (Text Template Transformation Toolkit) to read the model and generate SQL
script files to generate database objects for you.
1.8.1.4. A host of little things
As more developers use the new tools, they are finding other things that could make their
lives easier and have contributed to an MSDN Forum thread titled "V2 Wish List". You can
find a link to this thread on the Resources page of the book's website.
1.8.2. Challenges with change tracking distributed applications
To put it mildly, there are challenges when using Entity Framework in distributed
applications when it comes to the change tracking performed by Object Services. The cause
of this is the change tracking information is not stored in the entities. It is maintained by
a separate set of Object Services objects. When an entity is transferred across a process it
loses its association with the object that contains its change tracking information. And
Programming Entity Framework, 1st Edition Page 17 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
those objects which own the tracking data are not Serializable so they can't easily be
shipped across to the new process along with the entities. So when the entities arrive at
the new process, they have no idea if they are new or pre-existing, if they have been edited
or marked for deletion. There's no way to simply use the ObjectContext's default method
for saving changes to the database without doing additional work.
This problem is addressed and dissected in a number of places throughout this book with
a variety of coding patterns presented to help you succeed at moving entities around in
distributed applications such as Services or layers ASP.NET applications. Starting with
Chapter 8 which focuses on Object Services, many of the chapters throughout this book
provide detailed information about change tracking and working with entities across tiers
whether you use the ASP.NET Entity Data Source as in Chapter 10 or write a WCF Service
with Data Transfer Objects as in Chapter 22.
1.8.3. Domain Driven Development
As mentioned previously and noted in the subtitle of this book, Entity Framework Version
1's focus is data centric. Domain Driven Development begins with the model, not the
database. Many developers who embrace the tenets of Domain Driven design will find
Entity Framework to be too restrictive. However, some of the luminaries of this view of
applications are working with the Entity Framework team to enable Version 2 to expand
its capabilities so that it can be used with this approach.
1.8.4. Unit Testing
While it is possible to build Unit Tests with Entity Framework classes, the fact that entities
must either inherit from the EntityObject class or implement some of Object Services' key
interfaces makes it impossible to decouple the entity classes from the mechanism which
executes queries. Therefore, you cannot Unit Test your Entity Framework code without
causing the database to be accessed. Hitting the database while performing unit tests is
not a favorable option for most developers. Hopefully you wouldn't dream of testing
against the live database, but even with a copy, you would need to deal with rollbacks and
an assortment of other complications. Because of this, many developers have just written
Entity Framework off as "untestable".
One option, however, is to use a common unit testing technique called mocking. A tool
such as TypeMock Isolator (http:/www.typemock.com) which can automatically mock
desired objects, can help you in this quest. The next version of Entity Framework promises
to enable Unit Testing capabilities.
1.9. Programming Entity Framework
As you work through this book you will not only get the experience of designing EDMs and
using Entity Framework to write applications, but you will dig deeply into the APIs to learn
Programming Entity Framework, 1st Edition Page 18 Return to Table of Contents
Programming Entity Framework, 1st Edition
Programming Entity Framework, 1st Edition By Julia Lerman ISBN: 9780596156244
Publisher: O'Reilly Media, Inc.
Prepared for Dave Olsen, Safari ID: dave_olsen@logitech.com
Print Publication Date: 2009/01/15
User number: 1717051
© 2008 Safari Books Online, LLC. This PDF is made available for personal use only during the relevant subscription term, subject to the Safari Terms of Service. Any other use
requires prior written consent from the copyright owner. Unauthorized use, reproduction and/or distribution are strictly prohibited and violate applicable laws. All rights reserved.
how to manipulate entity objects and have granular control over much of its behavior.
There is a lot of functionality that is very accessible and there's a lot of power underneath
the covers. You will learn what's under the covers so that you can realize the true benefits
of the Entity Framework.
Chapter 2. Exploring the Entity Data Model
The Entity Data Model is the bridge between your application and your data store. It is the