Contents at a glanceIntroduction xvii PART I INTRODUCING THE ENTITY FRAMEWORK ChAPTEr 1 Getting to know the Entity Framework 3 ChAPTEr 2 Looking more closely at queries 29 PART II COMP
Trang 3Microsoft ADO.NET Entity Framework Step by Step
John Paul Mueller
Trang 4Published with the authorization of Microsoft Corporation by:
O’Reilly Media, Inc
1005 Gravenstein Highway North
Sebastopol, California 95472
Copyright © 2013 by John Mueller
All rights reserved No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher
ISBN: 978-0-735-66416-6
1 2 3 4 5 6 7 8 9 LSI 8 7 6 5 4 3
Printed and bound in the United States of America
Microsoft Press books are available through booksellers and distributors worldwide If you need support related
to this book, email Microsoft Press Book Support at mspinput@microsoft.com Please tell us what you think of this book at http://www.microsoft.com/learning/booksurvey
Microsoft and the trademarks listed at http://www.microsoft.com/about/legal/en/us/IntellectualProperty/ Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies All other marks are property of
their respective owners
The example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred
This book expresses the author’s views and opinions The information contained in this book is provided without any express, statutory, or implied warranties Neither the authors, O’Reilly Media, Inc., Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly
or indirectly by this book
Acquisitions and Developmental Editor: Russell Jones
Production Editor: Christopher Hearse
Editorial Production: Zyg Group, LLC
Technical Reviewer: Russ Mullen
Indexer: Zyg Group, LLC
Cover Design: Twist Creative • Seattle
Cover Composition: Ellie Volckhausen
Illustrator: Rebecca Demarest
Trang 5This book is dedicated to Kevin Smith, a good friend who’s helped us realize some of our most special dreams He’s always helped us help ourselves—an outstanding gift that’s exceptionally rare in this world.
—John Paul Mueller
Trang 7Contents at a glance
Introduction xvii
PART I INTRODUCING THE ENTITY FRAMEWORK
ChAPTEr 1 Getting to know the Entity Framework 3 ChAPTEr 2 Looking more closely at queries 29
PART II COMPLETING BASIC TASKS
PART III MANIPULATING DATA USING THE ENTITY FRAMEWORK
ChAPTEr 7 Manipulating data using entity SQL 147 ChAPTEr 8 Interaction with stored procedures 175
ChAPTEr 10 Interaction with Table-Valued Functions 213 PART IV OVERCOMING ENTITY ERRORS
ChAPTEr 12 Overcoming concurrency issues 265 ChAPTEr 13 handling performance problems 287 PART V ADVANCED MANAGEMENT TECHNIQUES
ChAPTEr 15 Mapping data types to properties 347 ChAPTEr 16 Performing advanced management tasks 369
Index 405
Trang 9Introduction xvii
PART I INTRODUCING THE ENTITY FRAMEWORK Chapter 1 Getting to know the Entity Framework 3 Defining an entity 4
Understanding the Entity Framework elements 6
Considering the conceptual model 7
Considering the storage model 8
Considering the model mappings 8
Introducing the Entity Framework files 9
Viewing the Conceptual Schema Definition Language file 9
Viewing the Store Schema Definition Language file 11
Viewing the Mapping Specification Language file .11
Developing a simple Entity Framework example .12
Starting the Entity Data Model Wizard 12
Using the Entity Data Model Designer 16
Working with the mapping details 18
Using the resulting framework to display data 22
Getting started with the Entity Framework 26
Chapter 1 quick reference 27
Chapter 2 Looking more closely at queries 29 Defining a basic query 30
Creating the model 30
Working with enumerations 31
Obtaining an application data source 33
Creating the test application 36
Running the basic query 39
Creating specific queries 41
Trang 10Using operators, properties, and methods 42
Combining and summarizing data .44
Grouping data 45
Getting started with the Entity Framework 47
Chapter 2 quick reference 48
Chapter 3 Choosing a workflow 49 Understanding the code-first workflow 51
Understanding the model-first workflow 53
Understanding the database-first workflow 54
Defining the workflow choices 55
Creating a code-first example .57
Creating a project .57
Defining the initial classes .58
Adding Entity Framework 5 support .59
Creating a code-first context 60
Adding a record .61
Viewing the results 63
Creating a model-first example 66
Defining the database model .66
Adding a record and viewing the results 70
Creating a database-first example 71
Reverse engineering the database model 71
Adding a record and comparing results .73
Getting started with the Entity Framework 74
Chapter 3 quick reference 75
PART II COMPLETING BASIC TASKS Chapter 4 Generating and using objects 79 Understanding the Entity objects .80
Considering object services 80
Trang 11Working with an EntityCollection 82
Understanding the role of Entity SQL .84
Making queries using objects 85
Considering the role of lambda expressions 86
Creating a basic query using Entity SQL .86
Creating a basic query using LINQ 88
Modifying data using objects 89
Adding the forms 90
Adding purchases 92
Updating purchases 93
Deleting purchases .95
Working with Query Builder methods .97
Getting started with the Entity Framework 98
Chapter 4 quick reference 99
Chapter 5 Performing essential tasks 101 Defining the essential tasks 101
Viewing the data 102
Saving changes 104
Inserting new values 104
Deleting old values .105
Creating a master/detail form 106
Creating the data source .106
Configuring the data source .109
Adding and configuring the controls 110
Testing the result 112
Getting started with the Entity Framework 114
Chapter 5 quick reference 114
PART III MANIPULATING DATA USING THE ENTITY FRAMEWORK Chapter 6 Manipulating data using LINQ 119 Introducing LINQ to Entities 120
Trang 12Developing LINQ to Entities queries 122
Defining the LINQ to Entities essential keywords 125
Defining the LINQ to Entities operators 127
Understanding LINQ compilation 135
Following an IQueryable sequence 135
Following a List sequence 138
Using entity and database functions 139
Creating the function .139
Accessing the function 142
Getting started with the Entity Framework 145
Chapter 6 quick reference 146
Chapter 7 Manipulating data using Entity SQL 147 Understanding Entity SQL 148
Considering the Entity SQL data flow 148
Defining the Entity SQL components 149
Selecting data 159
Working with literals in Entity SQL 161
Using the standard literals 161
Adding some additional data .162
Using a date or time literal 164
Interacting with a decimal literal 166
Ordering data 168
Grouping data 169
Getting started with the Entity Framework 171
Chapter 7 quick reference 172
Chapter 8 Interaction with stored procedures 175 Understanding stored procedures 176
Adding stored procedures to your model 179
Defining the stored procedure using Server Explorer 179
Testing the stored procedure 181
Trang 13Modifying a stored procedure 184
Building an application using stored procedures 188
Creating a basic stored procedure example .188
Getting started with the Entity Framework 191
Chapter 8 quick reference 192
Chapter 9 Interaction with views 193 Understanding views 194
Adding views to your model 196
Defining views using Server Explorer 196
Testing the view 198
Updating the model .200
Creating a basic view example 202
Making views writable 204
Getting started with the Entity Framework 210
Chapter 9 quick reference 211
Chapter 10 Interaction with Table-Valued Functions 213 Understanding TVFs 214
Comparing TVFs to views 214
Comparing TVFs to stored procedures .215
Defining the storage layer 215
Defining the mapping layer 216
Defining the conceptual layer 217
Defining the object layer .218
Adding TVFs to your model 218
Defining the TVF using Server Explorer 219
Testing the TVF 221
Updating the model .223
Calling a TVF using Entity SQL 225
Calling a TVF using LINQ 227
Mapping a TVF to an entity type collection .228
Trang 14Getting started with the Entity Framework 232
Chapter 10 quick reference 233
PART IV OVERCOMING ENTITY ERRORS Chapter 11 Dealing with exceptions 237 Understanding exceptions .238
Considering exception sources 240
Dealing with the System.Data.EntityException 240
Working through System.Data namespace exceptions 242
Working through System.Data.Common namespace exceptions 246
Working through System.Data.Linq namespace exceptions .247
Handling connection string exceptions .248
Seeing the connection string problem 248
Creating code for the connection string problem 250
Adding another layer of exception handling .253
Dealing with query exceptions 256
Dealing with other data exception types 258
Understanding concurrency exceptions 261
Getting started with the Entity Framework 262
Chapter 11 quick reference 263
Chapter 12 Overcoming concurrency issues 265 Visualizing database concurrency issues .266
Considering optimistic concurrency problems 268
Rejecting the change 269
Performing a partial update 270
Obtaining user input 270
Ignoring concurrency issues completely 270
Performing a forced update 271
Implementing optimistic concurrency in an application 271
Developing the test environment 272
Trang 15Testing the default concurrency 275
Coding for field changes 277
Using field-specific concurrency 279
Using row-version concurrency 282
Considering pessimistic concurrency issues 284
Getting started with the Entity Framework 285
Chapter 12 quick reference 286
Chapter 13 Handling performance problems 287 Understanding performance issue sources 288
Considering the layers 288
Retrieving too many records 289
Using the local cache 290
Relying on pregenerated views 290
Relying on precompiled queries 293
Disabling change tracking 294
Choosing between lazy loading and eager loading 294
Viewing performance issues 295
Direct query viewing 295
Using third-party products .301
Defining the performance triangle 302
Considering the effects of raw speed 303
Considering the effects of security 305
Considering how raw speed and security affect reliability 309
Using multithreading as an aid to speed 312
Getting started with the Entity Framework 315
Chapter 13 quick reference 316
PART V ADVANCED MANAGEMENT TECHNIQUES Chapter 14 Creating custom entities 319 Developing POCO classes 320
Configuring the model 320
Trang 16Adding the classes 322
Creating an ObjectContext class to interact with the POCO classes 325
Testing the POCO application 326
Creating a DbContext class to interact with the POCO classes 328
Creating the classes in a different project 330
Creating and using event handlers 337
Handling ObjectContext events 337
Creating and handling custom events 339
Creating custom methods 341
Creating custom properties .343
Getting started with the Entity Framework 345
Chapter 14 quick reference 346
Chapter 15 Mapping data types to properties 347 Understanding mapping automation configuration 348
Configuring properties 349
Changing property mapping 351
Filtering the data 352
Working with standard data types .354
Considering the standard data type mapping scenarios 354
Creating the Rewards3 database 355
Performing standard data type mapping 358
Working with enumerated data types .361
Working with complex data types 363
Working with geography and geometry spatial data types 366
Getting started with the Entity Framework 367
Chapter 15 quick reference 368
Chapter 16 Performing advanced management tasks 369 Developing multiple diagrams for a model 370
Creating the new diagram 371
Configuring the diagram appearance .374
Trang 17Performing batch imports of stored procedures and functions 376
Mapping a stored procedure that returns multiple result sets 377
Creating the stored procedure .378
Using the code-access technique 380
Using the EDMX modification technique 383
Creating entities with inheritance 387
Creating the Rewards4 database 387
Using inheritance with the model-first workflow 388
Using inheritance with the code-first workflow 394
Controlling context actions for automatically generated classes 400
Getting started with the Entity Framework 402
Chapter 16 quick reference 403
Index 405
Trang 19Gaining access to data in a managed way without a lot of coding—that’s a tall order!
The Entity Framework fulfills this promise and far more Each version of the Entity
Framework is more capable than the last The latest version, Entity Framework version 5,
provides you with access to far more database features with less work than ever before,
and Microsoft ADO.NET Entity Framework Step by Step is your gateway to finding just
how to use these phenomenal new features In this book, you get hands-on practice
with all the latest functionality that the Entity Framework provides By the time you
finish, you’ll be ready to tackle some of the most difficult database management tasks
without the heavy-duty coding that past efforts required
Fortunately, this book doesn’t get so immersed in high-end features that it forgets
to tell you how to get started Unlike a lot of tomes on the topic, this book starts simply
and helps you gain a good foothold in understanding just why the Entity Framework
is such an amazing addition to the your developer toolbox You’ll see examples where
the automation does just about everything for you with little coding required, and
yet you obtain professional-looking results In fact, that’s what you’re buying with the
Entity Framework—a reliable means of creating code quickly and successfully without
the problems that would ensue if you tried to create the same code completely by
hand The book’s 44 examples help you gain experience using the Entity Framework in
a hands-on environment where you actually create code, rather than just reading about
what might work
Of course, you do eventually delve into higher-end topics You’ll find an entire
chapter on one of the most requested features, Table-Valued Functions (TVFs) Access
to this feature alone makes the upgrade to Entity Framework 5 a significant one You’ll
also discover how to handle performance problems and perform low-end tasks such as
using inheritance when creating a model In short, by the time you finish this book, you
will have the experience required to handle every common task that developers need
to know how to perform
Who should read this book
Anyone who creates database applications using ADO.NET and is tired of writing reams
of code will definitely benefit from reading this book What you should ask yourself is
whether you want to become more productive while writing code that is both more
Trang 20reliable and better able to interact with the database Although the coding examples are written in C#, several Microsoft Visual Basic developers tested this book during the writing process and found that they could follow the examples quite well All you really need is a desire to write database applications more quickly and with less fuss.
Assumptions
To use this book successfully, you need a good knowledge of database programming concepts using a technology such as ADO.NET Although every attempt is made to ex-plain basic (and essential) topics, a knowledge of working with databases using the NET Framework will make working through the examples significantly easier
You also need to know how to write applications using the C# programming guage All of the examples are written using C#, and there isn’t any attempt to explain how the language elements work If you don’t have the required C# knowledge, you
lan-should consider getting John Sharp’s Microsoft Visual C# 2010 Step by Step (Microsoft
Press, 2010)
Some of the examples also require some knowledge of Transact-Structured Query Language (T-SQL) Again, there are plenty of comments provided with the various scripts, but there isn’t a lot of additional information provided about language ele-ments The book assumes that you know how basic SQL queries work
Who should not read this book
This book is most definitely not aimed at the complete novice You must know a little about both SQL and ADO.NET to work with the book successfully In addition, you must know the C# programming language fairly well The examples in the book focus a little more on enterprise developers, but hobbyists should be able to follow the examples without problem If you’re looking for a high-end book with lots of low-end program-ming examples and no hands-on techniques, this is most definitely not the book for you This book is all about getting people started using the Entity Framework in a meaningful way to perform most common tasks, which means it uses several different techniques to convey information so that a majority of readers can understand and use the material presented
Trang 21Organization of this book
This book is organized into five parts Each part is designed to demonstrate a
particu-lar facet of the Entity Framework, with an emphasis on the functionality provided by
version 5 Here is a brief overview of the book parts (each part introduction has more
detailed information about the content of the chapters in that part):
■
■ Part I: Introducing the Entity Framework This part of the book introduces
you to the Entity Framework version 5 You’ll discover what is new in this version
of the Entity Framework and also basic concepts such as the parts of a model
Unlike many other texts, this part also tells you about the three workflows
avail-able when working with the Entity Framework: model first, database first, and
code first Every chapter includes coding examples that emphasize the basics so
that you can see precisely how the Entity Framework works at a basic level
■
■ Part II: Completing basic tasks Once you have a basic understanding of
what the Entity Framework does and why you’d want to use it, it’s time to see
how to perform basic Create, Review, Update, and Delete (CRUD) operations
This part of the book provides an essential discussion of how to perform
es-sential tasks with full automation in place It’s the part of the book you want to
read to emphasize speed of development over flexibility in accessing database
functionality
■
■ Part III: Manipulating data using the Entity Framework Most applications
require more than a display of raw database data and simple CRUD operations
This part of the book takes the next step in your journey of actually controlling
how the data appears and precisely what data is retrieved from the database
You discover two client-side techniques for manipulating data (Language
Integrated Query [LINQ] and Entity Structured Query Language [Entity SQL])
In addition, you see how to use server-based techniques that include stored
procedures, views, and TVFs
■
■ Part IV: Overcoming entity errors It’s nearly impossible to create an
applica-tion that is free from error In fact, smart developers know that it is impossible
because you really never have full control over absolutely all of the code that
goes into your application This part of the book discusses three realms of error:
exceptions, concurrency issues, and performance problems
Trang 22■ Part V: Advanced management techniques This is the low-level-coding
part of the book This is where you learn how to create custom entities and use inheritance as a tool to create more robust models You also discover tech-niques for mapping various kinds of data to the Entity Framework, even when the Entity Framework normally doesn’t support the data type The key thing to remember about this part is that you discover manual methods for modifying how the automation works
Finding your best starting point in this book
The different sections of Microsoft® ADO.NET Entity Framework Step by Step cover a
wide range of technologies associated with the Entity Framework Depending on your needs and your existing understanding of Microsoft data tools, you may wish to focus
on specific areas of the book Use the following table to determine how best to proceed through the book
New to the Entity Framework Begin with Chapter 1, “Getting to know the
Entity Framework,” and move through Chapter
13, “Handling performance problems.” Skip the last part of the book until you have gained some experience using the automation that the Entity Framework provides.
Familiar with earlier releases of the Entity Framework Read through Chapter 1 and Chapter 3, “Choosing a workflow,” carefully Chapter 3 is
especially important because it helps you stand the new workflows Work through Parts III,
under-IV, and V as needed to update your knowledge Interested in learning advanced Entity Framework
techniques Move directly to Part V of the book The first four parts of this book are designed to help you learn
about the Entity Framework and interact fully with the automation it provides.
success-Interested in using the existing database structure of your organization Read Parts I and II to ensure you understand the basics of how the Entity Framework works, and
infra-then skip to Chapter 8, “Interaction with stored procedures,” Chapter 9, “Interaction with views,” and Chapter 10, “Interaction with table-valued functions.”
Every chapter in this book contains at least one hands-on example (and usually more) The only way you’ll actually gain a full understanding of the Entity Framework is
to download the sample code and then work through the hands-on examples Each of these procedures demonstrates an important element of the Entity Framework
Trang 23Conventions and features in this book
This book presents information using conventions designed to make the information
readable and easy to follow
Note Note boxed elements tell you about additional information that will prove
useful in working with the Entity Framework Notes normally include text about
techniques used to create examples or the sources of information used in creating
the chapter’s content
Tip Tip boxed elements provide additional information that will enhance your
productivity, make it easier to perform tasks, or help you locate additional sources
of information Most tips provide helpful information that you don’t need to know
in order to use the book, but the information will prove helpful later as you work
with real-world code
Warning Warning boxed elements describe potentially dangerous situations
where performing an act could result in damage to your application, the data it
manages, or the user environment (such as the need to keep certain types of
in-formation secure) Pay special attention to warning elements because they’ll save
you time and effort
■
■ Each exercise consists of a series of tasks, presented as numbered steps (1, 2,
and so on) listing each action you must take to complete the exercise
■
■ Sidebars contain useful information that isn’t part of the main flow of discussion
in a chapter These elements always have a title that tells you about the topic
of discussion You can safely skip sidebars if desired or simply read them later
Sidebars always provide you with helpful real-world resource information that
will help you as you create or manage applications
■
■ Text that you type (apart from code blocks) appears in bold
■
■ A plus sign (+) between two key names means that you must press those keys at
the same time For example, “Press Alt+Tab” means that you hold down the Alt
key while you press the Tab key
Trang 24■ A copy of Visual Studio 2012 Professional or better This book won’t work well with Visual Studio 2012 Express Edition In fact, many of the examples won’t work at all, even if you use the downloaded source code
■
■ A copy of Microsoft SQL Server 2012 Express Edition with SQL Server ment Studio 2012 Express or higher (included with Visual Studio) You can also use the full-fledged version of SQL Server 2012
Manage-Your computer must also meet these minimum requirements (although higher ings are always recommended):
Trang 25Note Many of the tasks in this book require that you have local administrator
rights Newer versions of Windows include stricter security that requires you
to have additional rights to perform tasks such as creating copies of database
files
Code samples
Most of the chapters in this book include exercises that let you interactively try out new
material learned in the main text All sample projects can be downloaded from the
fol-lowing page:
http://aka.ms/ADONETEFSbS/files
Follow the instructions to download the zip file
Note In addition to the code samples, your system should have Visual Studio
2012 Professional (or better) and SQL Server 2012 Express Edition (or better)
installed The exercises will include instructions for working with SQL Server
2012 In most cases, the exercises rely on Server Explorer to make it easy to
perform all tasks from the Visual Studio Integrated Development Environment
(IDE)
Installing the code samples
All you need to do to install the code samples is download them and unzip the archive
to a folder on your hard drive The complete source code file will include all of the
databases used in the book Simply attach these databases to your copy of SQL Server
or open them in Visual Studio by right-clicking Data Connections in Server Explorer and
choosing Add Connection Use the Microsoft SQL Server Database Connection option
when creating the connection If you encounter problems installing the code samples,
please contact me at John@JohnMuellerBooks.com You can also find answers to
com-mon questions for this book on my blog, at
http://blog.johnmuellerbooks.com/catego-ries/263/entity-framework-development-step-by-step.aspx.
Trang 26Using the code samples
The downloaded source code includes one folder for each chapter in the book Simply open the chapter folder and then the example folder for the example you want to work with in the book The downloaded source contains the completed source code so that you can see precisely how your example should look If you want to work through the examples from scratch, the book contains complete instructions for developing them.The downloaded source code also contains a Databases folder that contains all of the databases for the book Simply create a connection to the database you need to use The example will tell you which database is required If you desire, the exercises also tell you how to create the databases from scratch so that you can use whatever setup you like
Acknowledgments
Thanks to my wife, Rebecca, for working with me to get this book completed I really don’t know what I would have done without her help in researching and compiling some of the information that appears in this book She also did a fine job of proofread-ing my rough draft Rebecca keeps the house running while I’m buried in work
Russ Mullen deserves thanks for his technical edit of this book He greatly added to the accuracy and depth of the material you see here Russ is always providing me with great URLs for new products and ideas However, it’s the testing Russ does that helps most He’s the sanity check for my work Russ also has different computer equipment from mine, so he’s able to point out flaws that I might not otherwise notice
Matt Wagner, my agent, deserves credit for helping me get the contract in the first place and taking care of all the details that most authors don’t really consider I always appreciate his assistance It’s good to know that someone wants to help
A number of people read all or part of this book to help me refine the approach, test the coding examples, and generally provide input that all readers wish they could have These unpaid volunteers helped in ways too numerous to mention here I especially ap-preciate the efforts of Eva Beattie and Glenn Russell, who provided general input, read the entire book, and selflessly devoted themselves to this project
Trang 27Finally, I would like to thank my editor, Russell Jones; Christopher Hearse; Damon
Larson; and the rest of the editorial and production staff at O’Reilly for their assistance
in bringing this book to print It’s always nice to work with such a great group of
profes-sionals
Errata & book support
We’ve made every effort to ensure the accuracy of this book and its companion
con-tent Any errors that have been reported since this book was published are listed on our
Microsoft Press site at oreilly.com:
We want to hear from you
At Microsoft Press, your satisfaction is our top priority, and your feedback our most
valuable asset Please tell us what you think of this book at
http://www.microsoft.com/learning/booksurvey
The survey is short, and we read every one of your comments and ideas Thanks in
advance for your input!
Stay in touch
Let’s keep the conversation going! We’re on Twitter: http://twitter.com/MicrosoftPress.
Trang 29PART I
Introducing the Entity
Framework
Creating a database can be difficult A database models information in the real world using a
col-lection of tables, indexes, views, and other items In other words, a database is an abstraction of the
real-world information that it’s supposed to represent When a developer is tasked with creating an
application that relies on the data within a database, the developer must create a second level of
abstraction because the application won’t see the data in precisely the same way that the database
does Defining this second level of abstraction is even harder than creating the original database,
because it requires interpreting the real world through an abstraction In order to define a realistic
presentation of the data in the database—one that precisely represents the real world—a developer
needs help That’s what the Entity Framework does It provides help to a developer in the form of a
modeling methodology that eases the amount of work the developer must perform to create a
real-istic presentation To make things even easier, the Entity Framework relies on a graphical presentation
of the data so that the developer can literally see the relationships between the various tables and
other database items
Even though the concept of the Entity Framework is straightforward, you need to know more
about it before you can simply use it to create a connection between the database and your
applica-tion Working with models is definitely easier than working with hand-coded connections However,
you still need to have a good understanding of how those models work and the various ways you
can interact with them The purpose of the three chapters in this part is to introduce you to the Entity
Framework concepts You’ll use this information to build a picture of how the Entity Framework
per-forms its task so that you can perform more complex operations with the Entity Framework later in
the book
Trang 31■ Create a simple Entity Framework example.
When an architect wants to design a real-world building by creating a blueprint, one of the tools
used to ensure the blueprint is accurate is a model Often you see a model of the building as
part of the presentation for that building Models are helpful because they help others visualize the
ideas that reside in the architect’s head In addition, the models help the architect decide whether the
plan is realistic Likewise, software developers can rely on models as a means of understanding a
soft-ware design, determining whether that design is realistic, and conveying that design to others The
Entity Framework provides the means to create various kinds of models that a developer can interact
with in a number of ways As with the architect’s model, the Entity Framework uses a graphical
inter-face to make information about the underlying database structure easier to understand and modify
The Entity Framework is actually a Microsoft ActiveX Data Object NET (ADO.NET) technology
extension When you create the model of the database, you also make it possible for the Integrated
Development Environment (IDE) to automatically create some of the code required to make the
con-nection between an application and the database real Because of the way ADO.NET and the Entity
Framework interact, it’s possible to create extremely complex designs and then use those designs
directly from your code in a way that the developer will understand There isn’t any need to translate
between the levels of abstraction—the Entity Framework performs that task for you
Before you can begin using the Entity Framework to perform useful work, however, you need to
know a little more about it For one thing, you need to know why it’s called an Entity Framework It’s
also important to know how the various models work and how they’re stored on your system, should
you ever need to access them directly The following sections provide this information and more
about the Entity Framework You’ll then use the knowledge you’ve gained to create a very simple
ex-ample This example will help you better understand what the Entity Framework can do because you’ll
actually use it to interact with a simple database
Trang 32Defining an entity
An entity is the data associated with a particular object when considered from the perspective of
a particular application For example, a customer object will include a customer’s name, address, telephone number, company name, and so on The actual customer object may have more data than this associated with it, but from the perspective of this particular application, the customer object is complete by knowing these facts If you want to understand this from the traditional perspective of
a database administrator, the entity would be a single row in a view that contains all of the related information for the customer It includes everything that the database physically stores in separate tables about that particular client When thinking about entities, you need to consider these views of the data:
■
■ Physical The tables, keys, indexes, views, and other constructions that hold and describe the
data associated with a real-world object such as a customer All of these elements are mized to make it easier for the Database Management System (DBMS) to store and manipu-late the data efficiently and reliably, without error As such, a single customer data entry can appear in multiple tables and require the use of multiple keys to create a cohesive view of that customer The physical storage of the data is efficient for the DBMS, but difficult for the developer to understand
opti-■
■ Logical The combined elements required to define the data used with a single object, such
as a client From a database perspective, the logical view of the data is often encapsulated in a
view The view combines the data found within tables using keys and other database elements
that describe the relationships and order required to re-create the customer successfully Even
so, the logical view of a database is still somewhat abstract and could cause problems for the developer, not to mention require a lot of code to manage successfully ADO.NET does reduce the amount of coding the developer performs through the use of built-in objects, but the developer must still understand the underlying physical construction of that data
■
■ Conceptual The real-world view of the data as it applies to the object When you view a
customer, you see attributes that define the customer and remember items that describe the customer, such as the customer’s name A conceptual view of the data presents information in this understandable manner—as objects where the focus is on the data, not on the structure
of the underlying database
When you want to think about customers as a group, you work with entities Each entity is a single customer, and the customers as a group are entities as well In order to visualize the data that com-prises a customer, the Entity Framework relies on models These models help the developer concep-tualize the entities In addition, the Entity Framework stores these models in XML format for use in automatically generating code to create objects based on the models Working with objects makes life easier for the developer
Trang 33Note You may be tempted to think of the Entity Framework as a technology that only
ap-plies to Microsoft SQL Server and other relational databases The Entity Framework is a full solution that works with any data source, even flat-file and hierarchical databases For the sake of making the discussion clear, this book will rely upon SQL Server for the examples, but you should know that using SQL Server is only a convenience, and you can use the Entity Framework for any data source your application needs to work with In addition, you can mix and match data sources as needed within a single application
In times past, developers needed to consider the physical (tables), logical (views), and conceptual (data model) perspectives of data stored in a database A developer had to know precisely which table stored a particular piece of data, how that table was related to other tables in the database, and how to relate the data in such a way as to create a complete picture of a particular entity The developer then wrote code to make the connectivity between the application and the database work The Entity Framework reduces the need to perform such tasks A developer focuses on the entity, not the underlying physical or logical structure of the database that contains the data As a result, the developer is more productive Working with entities also makes the data easier to explain to others
An entity contains properties Just as objects are described by the properties they contain, entities
contain individual properties that describe each data element A customer’s last name would be a property of a customer entity Just as classes have configurable getters and setters, so do properties
in the Entity Framework Every entity has a special property called the key property The key property
uniquely defines the entity in some way An entity can have more than one key property, but it always has at least one An entity can also group multiple properties together to create a complex type that mimics the use of user-defined types with standard classes
Note It’s important to remember that properties can contain either simple or complex
data Simple data is of a type defined by the NET Framework, such as Int32 Complex data
is more akin to a user-defined type and consists of multiple base types within a like context
structure-It’s possible to create a relationship between two entities through an association For example, you might create an association between a customer entity and the order entities associated with the cus-tomer The association type defines the specifics of the association In some respects, an association
is similar to a database-level join One or more properties in each entity, called association endpoints,
define the relationship between the two entities The properties can define both single and umn connections between the two entities The multiplicity of the association endpoints determines whether the association is one-to-one, one-to-many, or some other combination The association
Trang 34multicol-is bidirectional, so entities have full access to each other In addition, an entity association can exmulticol-ist even when the target data lacks any form of database-level join specification All of the association
instances used to define an association type make up what is called the association set.
In order to allow one entity to view the data provided by an associated entity, the entities have a navigation property For example, a customer entity that’s associated with multiple order entities will have a navigation property that allows each order to know that it’s associated with that customer Likewise, each order will have a navigation property that allows each customer entity to see all of the orders associated with it The use of navigation properties allows your code to create a view of the en-tities from the perspective of a particular entity When working with a customer entity, the application can gain access to all of the orders submitted by that customer In some respects, this feature works much like a foreign key does in a database, but it’s easier to work with and faster to implement.Some entities derive from other entities For example, a customer can create an order However, the order will eventually have a state that creates other entities, such as a past-due order entity or a delivered-order entity These derived entities exist in the same container as the order entity as part of
an entity set You can view the relationship between entities and derived entities as being similar to
a database and its views The database contains all of the data, but a view looks at the data in a ticular way In the same way, a derived entity would help you create applications that view a particular entity type within the set of entities
par-The final piece of information you need to know for now about entities concerns the entity tainer In order to provide a convenient means to hold all of the entity information together, the Entity
con-Framework employs the entity container Before you can interact with an entity, your application
cre-ates an entity container instance This instance is known as the context Your application accesses the
entities within a particular context
Understanding the Entity Framework elements
The Entity Framework relies on XML files to perform its work These files perform three tasks: ing the conceptual model, defining the storage model, and creating mappings between the models and the physical database Even though the Entity Framework does a lot of the work for you, it’s still important to understand how these elements work together to create a better environment in which
defin-to write applications
Trang 35Note This chapter discusses the idea of models generically However, it’s important to
real-ize that the Entity Framework lets you interact with the database using one of three niques:
tech-■
■ Database first The Entity Framework creates classes that reflect an existing database
design
■
■ Design first You define a model of the database that the Entity Framework then creates
on the database server
■
■ Code first You create an application, and the Entity Framework defines a model that it
then uses to create the database on the database server
In all three cases, the Entity Framework eventually creates a model that follows the dards described in this chapter You’ll learn more about the methods of working with the Entity Framework in Chapter 3, “Choosing a workflow.” For now, the important consider-ation is the model itself
stan-Now that you a have a little idea of what constitutes the Entity Framework elements, it’s time
to discuss them in greater detail In this case, we’re looking at the logical structure of the Entity Framework The physical structure (the XML files and their content) is discussed in the “Introduc-ing the Entity Framework files” section of the chapter The following sections discuss the conceptual model, storage model, and model mappings
Considering the conceptual model
The conceptual model is the part of the Entity Framework that developers interact with most This model defines how the database looks from the application’s perspective Of course, the application view must somehow match the physical realities of the underlying database, but there are many ways
in which this happens For example, a C# application will use an INT32 value, rather than the tured Query Language (SQL) int type The conceptual model will refer to the data type as INT32, but the reality is that the database itself stores the data as an int.
Struc-The conceptual model is also used to create the classes used to interact with the database Struc-The Entity Framework manages the conceptual model As you make changes to the conceptual model, the changes are reflected in both the classes that the Entity Framework creates for your application and in the structure of the database In addition, the Entity Framework automatically tracks changes to the database design and incorporates them into your implementation classes As a result, your application can always access the data and functionality included with the target database
Trang 36Note It’s important to realize that changes to the database design can occur at several
levels The two most common levels are from the developer, when making changes to
the database model to accommodate application requirements; and from the Database Administrator (DBA), to accommodate enterprise-wide changes to the database as needed
to efficiently and reliably store information No matter how a change occurs, the database structure is ultimately affected, at which point the Entity Framework detects the change and updates the application using the data
A conceptual model also incorporates the concept of a namespace, just as your applications do An Entity Framework namespace performs the same functions as the namespace in your application For example, it helps define entities with the same name as unique features Using namespaces also helps group like entities together For example, everything related to a customer can appear in the same namespace, making it easier to interact with the customer in every way needed
At the heart of the conceptual model are the entity and association definitions used to create the view of the database Each entity definition includes the information described in the “Defining an entity” section earlier in this chapter When you use the designer to interact with the database model, what you’re really doing is modifying the XML entries that create and define each of these entity definitions The XML entries are stored on disk and used to re-create the graphic appearance of the model when you reopen the project
Considering the storage model
The storage model is the part of the Entity Framework that defines how the database looks from the database manager’s perspective However, this model provides this view within Microsoft Visual Studio, and it provides support for the conceptual model This model is often called the logical model because it provides a logical view of the database that ultimately translates into the physical database (see the “Defining an entity” section earlier in this chapter for a description of the various database views)
As with the conceptual model, the storage model consists of entity and association definitions However, these definitions reflect the logical appearance of the actual database, rather than the presentation of the conceptual model within the application In addition to the entity and association definitions, the storage model includes actual database data such as commands used to query the information within the database You’ll also find stored procedures in this model All of this additional information is used by ADO.NET to create connection and command objects automatically, so that you don’t have to hand-code the information as part of your application
Considering the model mappings
At this point, you know that there are two models used with the Entity Framework—the conceptual model presents the application view of the database and the storage model presents the logical database manager view of the database These two models are necessarily different If they were the
Trang 37same, you wouldn’t need two models The need for two models is also easy to understand once you consider that the application’s use of the database is always going to differ from the database manag-er’s goals of storing the data efficiency and reliably In order to make the two models work together, the Entity Framework requires model mapping—a third element that describes how something in the conceptual model translates to the storage model, and vice versa.
The overall goal of the model-mapping part of the Entity Framework is to create a definition of how the entities, properties, and associations in the conceptual model translate to elements within the storage model This mapping makes it possible for the application to create a connection to the database, modify its structure, manage data, and perform other tasks with a minimum of manually written code Most of the code used to interact with the database is automatically generated for the developer using the combination of the conceptual model, storage model, and this mapping layer
Introducing the Entity Framework files
As previously mentioned, all of the files used with the Entity Framework rely on XML The use of XML makes the files portable and easy to use with other applications You can also view the content of these files and reasonably expect to understand much of what they contain However, each of the Entity Framework elements uses a different XML file with a different file extension and a different language inside
After you create a new application that relies on the Entity Framework and define the required database models, you can find the resulting files in the main folder of the project When working with Visual Studio 2012, you’ll find a single Entity Data Model XML (.EDMX) file However, when working with older versions of Visual Studio, you may find individual files for each of the Entity Framework elements
Providing a complete tutorial on each of these files is outside the scope of this book The following sections provide a useful overview of the files, which you can use for further study
Viewing the Conceptual Schema Definition Language file
The Conceptual Schema Definition Language (.CSDL) file contains the XML required to build the ceptual model of the database content as viewed by the application You see this content in graphi-cal format when working with Visual Studio To see it in plain-text form, locate the CSDL or EDMX file for your application in the project folder Right-click this file in Microsoft Windows Explorer and choose Open With from the context menu Locate Notepad or some other suitable text editor in the Open With dialog box, clear any option that says that this program will become the default program for opening this file, and click OK You’ll see the XML for the conceptual model for the application
con-Following is the XML for the sample application that appears later in the chapter (some <Schema>
attributes are removed to make the listing easier to read)
Trang 38Note When using Visual Studio design tools to create the CSDL, Store Schema Definition
Language (.SSDL), and Mapping Specification Language (.MSL) files, all three are stored in
a single EDMX file, rather than in separate files Whether the data appears in a single file or within multiple files, it’s always stored as XML An EDMX file also contains some designer information not found in the separate files You can safely ignore the designer information when viewing the EDMX file in order to understand how the conceptual model, storage model, and model mapping interact
<! CSDL content >
<edmx:ConceptualModels>
<Schema xmlns="http://schemas.microsoft.com/ado/2009/11/edm" >
<EntityContainer Name="Model1Container" annotation:LazyLoadingEnabled="true">
<EntitySet Name="Customers" EntityType="Model1.Customer" />
<Property Type="String" Name="FirstName" Nullable="false" />
<Property Type="String" Name="LastName" Nullable="false" />
<Property Type="String" Name="AddressLine1" Nullable="false" />
<Property Type="String" Name="AddressLine2" Nullable="false" />
<Property Type="String" Name="City" Nullable="false" />
<Property Type="String" Name="State_Province" Nullable="false" />
<Property Type="String" Name="ZIP_Postal_Code" Nullable="false" />
<Property Type="String" Name="Region_Country" Nullable="false" />
</EntityType>
</Schema>
</edmx:ConceptualModels>
The XML makes it easier to understand the preceding discussion of how an Entity object works
Notice that the XML describes an entity container, used to hold all of the entities for this particular
model Within that container is a single EntityType named Customer As with all Entity objects, this one has a Key property named CustomerID that gives the Entity a unique value In addition, there are
a number of properties associated with this Entity, such as FirstName You’ll see how the properties work later in the chapter Of course, an Entity can have other elements associated with it, and you’ll
see them at work later in the book
Look at the individual <Property> entries Each one includes a NET type In this case, the types are limited to Int32 and String, but you have access to a number of other types You can see the primitive data types supported by the Entity Framework at http://msdn.microsoft.com/library/ee382832.aspx.
Trang 39Viewing the Store Schema Definition Language file
The SSDL file contains the XML required to define the storage model of the database content as viewed by the database manager As with the conceptual model, you see the database described in terms of the entities required to create it The entries rely on SQL data types, rather than NET data types Here’s an example of the XML used to create a storage model for the example that appears
later in the chapter (the <Schema> has been shortened to make the text easier to read):
<Property Name="FirstName" Type="nvarchar(max)" Nullable="false" />
<Property Name="LastName" Type="nvarchar(max)" Nullable="false" />
<Property Name="AddressLine1" Type="nvarchar(max)" Nullable="false" />
<Property Name="AddressLine2" Type="nvarchar(max)" Nullable="false" />
<Property Name="City" Type="nvarchar(max)" Nullable="false" />
<Property Name="State_Province" Type="nvarchar(max)" Nullable="false" />
<Property Name="ZIP_Postal_Code" Type="nvarchar(max)" Nullable="false" />
<Property Name="Region_Country" Type="nvarchar(max)" Nullable="false" />
</EntityType>
Viewing the Mapping Specification Language file
The MSL file creates a relationship between the CSDL and SSDL files The mapping serves to define how the application view and the database manager view reflect the same database, but from differ-ing perspectives For example, the model mapping defines which conceptual model property trans-lates into a particular storage model property Here’s the model-mapping content for the example that appears later in the chapter:
Trang 40<MappingFragment StoreEntitySet="Customers">
<ScalarProperty Name="CustomerID" ColumnName="CustomerID" />
<ScalarProperty Name="FirstName" ColumnName="FirstName" />
<ScalarProperty Name="LastName" ColumnName="LastName" />
<ScalarProperty Name="AddressLine1" ColumnName="AddressLine1" />
<ScalarProperty Name="AddressLine2" ColumnName="AddressLine2" />
<ScalarProperty Name="City" ColumnName="City" />
<ScalarProperty Name="State_Province" ColumnName="State_Province" />
<ScalarProperty Name="ZIP_Postal_Code" ColumnName="ZIP_Postal_Code" />
<ScalarProperty Name="Region_Country" ColumnName="Region_Country" />
Developing a simple Entity Framework example
The best way to begin learning about the Entity Framework is to use it This example won’t do thing too spectacular In fact, it’s downright mundane, but it does reflect a process that many devel-opers use to experiment with the Entity Framework In this case, you’ll use the model-first technique
any-to create an example application Remember that in the model-first approach, you begin by creating
a model that’s then added to the database, rather than relying on an existing database to define the model The model-first technique has the advantage of allowing you to create and manipulate a data-base that won’t have any impact on anyone else, so you’re free to experiment as much as you want.The example will start with a Windows Forms application You’ll create the model needed to make the database work with SQL Server Express (installed automatically on your system), and then use the resulting model to create a functional application You’ll test the application by managing some data you create with it The entire process will take an amazingly short time to complete, as described in the following sections
Starting the Entity Data Model Wizard
The first step is to create the database model You can perform this task using a number of methods, most of which developers never use The easy method is to start the Entity Data Model Wizard and have it do the work for you That’s the approach this example takes, as described in the following steps (you can find this project in the \Microsoft Press\Entity Framework Development Step by Step\Chapter 01\SimpleEF folder of the downloadable source code):