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

Introducing the Entity Framework

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

Chapter 13
Introducing the Entity Framework
After completing this chapter, you will be able to:

Understand the high-level concepts of the ADO.NET Entity Framework

Distinguish between the three main Entity Framework modeling layers

Identify the general relationships between database elements and parallel elements in
the Entity Framework
ADO.NET has been included with the .NET Framework since its initial release in 2002. As the
primary data layer of the Framework, it provides great general-purpose access to external
data sources. Starting with Service Pack 1 of Visual Studio 2008 (and the associated .NET
Framework version 3.5), Microsoft enhanced ADO.NET with a library of additional function-
ality known as the Entity Framework (EF). The question is this: Why? Why would Microsoft
augment a system that already provided sufficient features to work with both internal and
external data in a generic, convenient format?
This chapter answers that question by introducing the Entity Framework and its major con-
ceptual components. It focuses on the two primary benefits of using the Framework on top
of ADO.NET’s core data functionality: (1) the ability to focus on the conceptual view of how
data fits together instead of on the physical view of how it is stored in the database; and (2)
the move away from the database-centric reality of independent tables joined in relation-
ship toward a true object-oriented model in which related data values are treated as integral
members of each other’s data worldviews.
Note
The four EF-related chapters in this book offer only a brief introduction to the flexible
and extensive Entity Framework. For expanded coverage of the Framework and how to use it
in your projects, review the Visual Studio online help. The Microsoft Press book Programming
the Microsoft® ADO.NET Entity Framework provides a more detailed exploration of EF and its
components.
Understanding the Entity Framework


ADO.NET provides convenient programmer access to content located in an external data
source or crafted within the application. One of the data layer’s core strengths is its capabil-
ity to simulate the logical implementation of the underlying data source. Database tables
Dwonloaded from: iDATA.ws
214
stored in a relational database such as SQL Server can be brought into an application, com-
plete with constructs that emulate the join relationships and columnar data types of each
imported table. Foreign keys play an important role in bringing data together, both in the
database and in the DataSet representation.
By processing the data that comes into your program through a DataReader or by adjusting
the TableMapping rules associated with a DataAdapter, you can modify the presentation of
the incoming data structures from the way they appear in the underlying database. Yet even
with such modifications, many DataSet and DataTable representations of external data tend
to resemble the logical view of the source data.
When working with tables of customers and orders, an associated DataSet will often con-
tain Customer and Order DataTable objects that are little more than local copies of the true
tables. Although this benefit is very useful for developers focused on a specific database
schema, it is also a disadvantage, especially when changes to the external schema must be
constantly reflected in code. The table-specific focus of the DataSet also forces applications
to work with data according to the dictates and limitations of the database, instead of on the
enhanced features that languages such as C# and Visual Basic bring to the data processing
table. Additionally, ADO.NET’s use of generic object collections for row values removes the
strongly typed benefits of programming in .NET.
Note
Visual Studio 2005 and version 2.0 of the .NET Framework introduced strongly typed
DataSets. These wizard-generated classes, derived from DataSet and ADO.NET’s other discon-
nected table classes, added imported table and column definitions as true class members.
Strongly typed data sets are still available in Visual Studio 2010. However, the Entity Framework
provides enhanced database interaction capabilities and additional features that often make it a
better option for defining strongly typed views of external data. Strongly typed data sets are not

discussed further in this book.
The Entity Framework helps resolve such issues by putting the focus on the conceptual
implementation of the data; a class-based view of how all the data works together. Instead
of working with distinct table records that refer to each other’s records indirectly through
foreign key values, EF objects expose these relationships as true object-oriented class mem-
berships. Where a DataSet may contain separate Customer and Order tables that need to
have their records joined manually in code, a Customer entity class generated by the Entity
Framework includes an OrderEntries member, with each customer instance already aware of
its associated orders. Foreign keys are still important, but the Framework figures out how to
use them, leaving code free to access the results in a true instance-based environment.
Dwonloaded from: iDATA.ws
Chapter 13 Introducing the Entity Framework
215
Defining the Entity Framework’s Terms
The Entity Framework works with different types of flat, relational, and hierarchical data
sources—not just traditional databases such as SQL Server—so the names used for the dif-
ferent components of the Framework were selected to reflect those different usage options.
Still, in light of its standard ADO.NET underpinnings and its excellent support for SQL Server
and similar databases, it is helpful to understand its features as they relate to relational data-
base concepts.

Model The Entity Framework is, above all, a system for designing conceptual mod-
els of your data. These models are saved in an XML format from which the Framework
generates the specific source code classes. All terms defined here (entity, association,
and so on) are primarily model-based, although the Framework generates classes and
code that makes them more than just items in a model diagram.

Entity The core of the Entity Framework is, naturally, the Entity. With its ADO.NET
core, you might think, incorrectly, that an entity finds its parallel in the DataSet or
DataTable. Instead, the parallel for an entity is a single table row, a record, a DataRow.

A customer entity is a single customer, with a distinct name, address, set of orders, and
so on. The Framework generates the custom classes (known as Entity Types) from which
specific entity objects are instantiated.

Entities The plural form of an entity has a separate existence in the Entity Framework,
implemented as a generic collection of a specific entity. Similar in concept to a table
or a DataTable, entities are created by the Framework to expose enumerable instances
of a specific custom entity. This parent-child relationship smoothes the transition from
table-row-style database content to inheritable class-based data management.

Property The field or column members of an entity (similar to DataColumn instances
in a DataTable) are known as properties. This makes sense because they are imple-
mented as standard class properties, complete with configurable getters and setters.
One or more properties in an entity are designated as the entity key, which uniquely
defines each entity. All entities require an entity key. Multiple properties can be defined
together as a complex type, sort of a user-defined data type for entities.

Association A relationship established between two entities is known as an associa-
tion, and is defined through an association type. Similar to a database-level table join
or a DataRelation in standard ADO.NET, associations define the single or multicolumn
connections between different entities. The properties on either end of the relation-
ship are known as association ends. The cardinality of an association (or in EF parlance,
the multiplicity of its association endpoints; whether the association is one-to-one,
one-to-many, and so on) helps determine how the association exposes data. Unlike the
DataRelation implementation, associations are true bidirectional access points between
entity instances. An entity can exist even if the tables that provide the content for asso-
ciated entities lack a database-level join specification.
Dwonloaded from: iDATA.ws
216
Microsoft ADO.NET 4 Step by Step


Association set All association instances for a defined association type appear as a
distinct collection called an association set. On the model side of the Framework, an
association set contains the field definitions that describe a single association between
two tables.

Navigation property A navigation property exposes the available data at the other
end of an association. For instance, in a customer-order association, the Orders naviga-
tion property on a Customer entity object provides access to the zero or more Order
entity instances associated with the specific customer. When viewed from the order side
of that same relationship, a customer-targeted navigation property on an Order entity
instance links to the Customer object to which that order belongs. An entity can also
contain foreign keys to an associated entity, but these keys provide less direct access to
related data.

Entity set An entity set is the logical container for an entity and any other entities de-
rived from that first entity. For example, a PastDueOrder entity definition and the Order
definition from which it derives would appear together in a single entity set. The closest
parallel in a relational database might be a table and any views created that use only
content from that base table.

Entity container One or more entity sets appear within the context of an entity con-
tainer, the outermost conceptual construct within the Entity Framework. When writing
code that interacts with entities, you will always start by creating an instance of an entity
container, known as a context. The entity container is a lot like a database or DataSet,
each with its collection of tables (entities).
Entity Framework models define an entity container, which in turn includes entity sets and as-
sociation sets. An entity set contains one or more (derived) entity types. Entities are defined
by their properties, both simple and complex. The definition of an association always includes
the two endpoints that join related entities. Classes generated by the Framework implement

in code the entities, properties, and associations defined in the model.
Understanding the Entity Framework’s Layers
In the Entity Framework, you define all the entities, associations, entity sets, and so on
through XML schema dialects. The Framework uses the XML-defined model to generate
classes in Visual Basic or C#. These classes implement the data environment described by
the model. Each model includes three main layers that help isolate the programmatic access
to the data from the database-managed storage of the raw data. The three layers are the
conceptual model (or conceptual layer), the storage model (storage layer), and the mappings
(mapping layer).
Dwonloaded from: iDATA.ws
Chapter 13 Introducing the Entity Framework
217
Understanding the Conceptual Model
For developers, the conceptual model is frequently the primary focus in setting up an Entity
Framework experience. This layer defines the Entity Data Model (EDM), the data organiza-
tion concepts that will find their way into generated application-side instantiated classes. The
conceptual model is defined with the Conceptual Schema Definition Language (CSDL), which
is an XML schema definition. In your project, CSDL files have a .csdl extension.
Note
As discussed in the following text and in the next chapter, models generated using Visual
Studio design tools store the resulting XML content in a file with an .edmx file extension. The
XML specifications for the three model layers all appear in this single file instead of in separate
files with their own file extensions.
Whenever the model changes, the Framework can generate a new set of implementation
classes, simplifying the process of propagating database-level changes into your application’s
source code.
Each model defines a namespace in which its entities, associations, and other key compo-
nents appear. Like standard .NET namespaces, EF namespaces help group related entities
under a common name and allow for differentiation between otherwise identically named
entities.

Note
Visual Studio includes a Generate Database Wizard that can use a valid CSDL model to
generate a SQL Server database with all needed tables and supporting elements. Use of the wiz-
ard is beyond the scope of this book. For information on this tool, search for “Generate Database
Wizard” in the Visual Studio 2010 online help.
Understanding the Storage Model
The storage model identifies the underlying database-level elements that support the
conceptual model. Sometimes called the logical model, the storage model layer defines
the application-side experience of a database-side logical (and ultimately, physical)
implementation.
Like the conceptual model, the storage model includes entity and association definitions in a
model-language syntax, independent of any specific database. But it also contains database-
specific commands (queries and stored procedures) that will eventually find their way to
ADO.NET connection and command objects.
Your code defines the storage model using the Store Schema Definition Language (SSDL),
another XML schema definition. SSDL files use the extension .ssdl.
Dwonloaded from: iDATA.ws

×