introducing the entity framework

Upload: benben00727

Post on 06-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Introducing the Entity Framework

    1/21

    Introducing the Entity Framework

    The Entity Framework is a set of technologies in ADO.NET that support development of data-oriented softwareapplications. Architects and developers of data-oriented applications have struggled with the need to achieve two ve

    different objectives. They must model the entities, relationships, and logic of the business problems they are solving

    and they must also work with the data engines used to store and retrieve the data. The data may span multiple storagystems, each with its own protocols; even applications that work with a single storage system must balance the

    equirements of the storage system against the requirements of writing efficient and maintainable application code.

    The Entity Framework enables developers to work with data in the form of domain-specific objects and properties,

    uch as customers and customer addresses, without having to concern themselves with the underlying database tableand columns where this data is stored. This is enabled by elevating the level of abstraction at which developers can

    work when they deal with data and reducing the code that is required to create and maintain data-oriented applicatio

    Because the Entity Framework is a component of the .NET Framework, Entity Framework applications can run on aomputer on which the .NET Framework 3.5 Service Pack 1 (SP1) is installed.

    Giving Life to Conceptual Models

    A longstanding and common design pattern for data modeling is the division of the data model into three parts: a

    onceptual model, a logical model, and a physical model. The conceptual model defines the entities and relationshiphe system that is being modeled. The logical model for a relational database normalizes the entities and relationship

    nto tables with foreign key constraints. The physical model addresses the capabilities of a particular data engine by

    pecifying storage details such as partitioning and indexing.

    The physical model is refined by database administrators to improve performance, but programmers writing applica

    ode primarily confine themselves to working with the logical model by writing SQL queries and calling storedprocedures. Conceptual models are generally used as a tool for capturing and communicating the requirements of an

    application, frequently as inert diagrams that are viewed and discussed in the early stages of a project and thenabandoned. Many development teams skip creating a conceptual model and begin by specifying tables, columns, an

    keys in a relational database.

    The Entity Framework gives life to conceptual models by enabling developers to query entities and relationships in

    onceptual model while relying on the Entity Framework to translate those operations to data source-specificommands. This frees applications from hard-coded dependencies on a particular data source. The conceptual mode

    he storage model, and the mapping between the two are expressed in an external specification, known as the Entity

    Data Model (EDM).The storage model and mappings can change as needed without requiring changes to the

    onceptual model, data classes, or application code. Because storage models are provider-specific, you can work wionsistent conceptual model across various data sources.

    An EDM is defined by the following three model and mapping files that have corresponding file name extensions:

    Conceptual schema definition language file (.csdl) - defines the conceptual model.

    Store schema definition language file (.ssdl) - defines the storage model, which is also called the logical mod

    Mapping specification language file (.msl) - defines the mapping between the storage and conceptual models

  • 8/3/2019 Introducing the Entity Framework

    2/21

    The Entity Framework uses these XML-based model and mapping files to transform create, read, update, and delete

    operations against entities and relationships in the conceptual model to equivalent operations in the data source. The

    EDM even supports mapping entities in the conceptual model to stored procedures in the data source. For morenformation, see Data Modeling in the Entity Framework.

    Mapping Objects to DataObject-oriented programming poses a challenge for interacting with data storage systems. Although the organizationlasses frequently closely mirrors the organization of relational database tables, the fit is not perfect. Multiple

    normalized tables frequently correspond to a single class, and relationships between classes are represented differen

    from relationships between tables. For example, to represent the customer for a sales order, an Order class uses a

    property that contains a reference to an instance of a Customer class, but an Order table row in a database containsforeign key column (or set of columns) with a value that corresponds to a primary key value in the Customer table.

    Customer class might have a property named Orders that contains a collection of instances of the Order class, but

    Customer table in a database has no comparable column.

    Existing solutions have tried to bridge this gap, which is frequently called an "impedance mismatch", by only mapp

    object-oriented classes and properties to relational tables and columns. Instead of taking this traditional approach, th

    Entity Framework maps relational tables, columns, and foreign key constraints in logical models to entities and

    elationships in conceptual models. This enables greater flexibility both in defining objects and optimizing the logicmodel. The Entity Data Model tools generate extensible data classes based on the conceptual model. These classes a

    partial classes that can be extended with additional members that the developer adds. The classes that are generated

    a particular conceptual model derive from base classes that provide Object Services for materializing entities as objeand for tracking and saving changes. Developers can use these classes to work with the entities and relationships as

    objects related by navigation properties. For more information about Object Services, see Object Services Overview

    Entity Framework).

    Accessing and Changing Entity Data

    More than just another object-relational mapping solution, the Entity Framework is fundamentally about enabling

    applications to access and change data that is represented as entities and relationships in the conceptual model. Obje

    Services uses the EDM to translate object queries against entity types that are represented in the conceptual model indata source-specific queries. Query results are materialized into objects that Object Services manages. The Entity

    Framework provides the following ways to query an EDM and return objects:

    LINQ to Entities - provides Language-Integrated Query (LINQ) support for querying entity types that are

    defined in a conceptual model. For more information, see LINQ to Entities Overview. Entity SQL - a storage-independent dialect of SQL that works directly with entities in the conceptual model

    that supports EDM features such as inheritance and relationships. Entity SQL is used both with object querie

    and queries that are executed by using the EntityClient provider. For more information, seeEntity SQLOverview.

    Query builder methods - enables you to construct Entity SQL queries using LINQ-style query methods. For

    more information, see Query Builder Methods (Entity Framework).

    http://msdn.microsoft.com/en-us/library/bb399183.aspxhttp://msdn.microsoft.com/en-us/library/bb386871.aspxhttp://msdn.microsoft.com/en-us/library/bb386871.aspxhttp://msdn.microsoft.com/en-us/library/bb386992.aspxhttp://msdn.microsoft.com/en-us/library/bb387145.aspxhttp://msdn.microsoft.com/en-us/library/bb387145.aspxhttp://msdn.microsoft.com/en-us/library/bb387145.aspxhttp://msdn.microsoft.com/en-us/library/bb387145.aspxhttp://msdn.microsoft.com/en-us/library/bb896238.aspxhttp://msdn.microsoft.com/en-us/library/bb896238.aspxhttp://msdn.microsoft.com/en-us/library/bb399183.aspxhttp://msdn.microsoft.com/en-us/library/bb386871.aspxhttp://msdn.microsoft.com/en-us/library/bb386871.aspxhttp://msdn.microsoft.com/en-us/library/bb386992.aspxhttp://msdn.microsoft.com/en-us/library/bb387145.aspxhttp://msdn.microsoft.com/en-us/library/bb387145.aspxhttp://msdn.microsoft.com/en-us/library/bb896238.aspx
  • 8/3/2019 Introducing the Entity Framework

    3/21

    The Entity Framework includes the EntityClient data provider. This provider manages connections, translates entity

    queries into data source-specific queries, and returns a data reader that Object Services uses to materialize entity dat

    nto objects. When object materialization is not required, the EntityClient provider can also be used like a standardADO.NET data provider by enabling applications to execute Entity SQL queries and consume the returned read-onl

    data reader. For more information, see EntityClient Provider for the Entity Framework.

    The following diagram illustrates the Entity Framework architecture for accessing data:

    The Entity Framework generates a class derived fromObjectContext that represents the entity container in the

    onceptual model. This object context provides the facilities for tracking changes and managing identities,oncurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and dele

    o the data source. Like queries, these changes are either made by commands automatically generated by the system

    by stored procedures that are specified by the developer. For more information, see Adding, Modifying, and Deletin

    Objects (Entity Framework).

    Entity Data Model Tools

    Together with the Entity Framework runtime, the .NET Framework 3.5 SP1 includes EDM Generator (EdmGen.exe

    This command prompt utility connects to a data source and generates an EDM based on a one-to-one mapping betw

    http://msdn.microsoft.com/en-us/library/bb738561.aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspxhttp://msdn.microsoft.com/en-us/library/bb738561.aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspx
  • 8/3/2019 Introducing the Entity Framework

    4/21

    ntities and tables. It also uses a conceptual model file (.csdl) to generate an object layer file that contains classes tha

    epresent entity types and the ObjectContext. For more information, see EDM Generator (EdmGen.exe).

    Visual Studio 2008 includes rich tool support for generating and maintaining an EDM in a Visual Studio applicationThe Entity Data Model Designer supports creating advanced mapping scenarios, such as table-per-type and table-pe

    hierarchy inheritance and split entities that map to multiple tables. For more information, seeADO.NET Entity DataModel Designer Overview.

    ADO.NET Entity Data Model Designer Overview

    The ADO.NET Entity Data Model Designer (Entity Designer) is a visual tool that enables point-and-click modificat

    of an EDM. You can use the Entity Designer to visually create and modify entities, associations, mappings, and

    nheritance relationships. You can also validate an EDM.

    The Entity Designer works together with the Entity Data Model Wizard and Update Model Wizard to allow you to

    generate, edit, and update an EDM.

    The Entity Designer consists of the following components:

    A visual design surface for editing the conceptual model. You can create, modify, or delete entities and

    associations.

    A Mapping Details window for viewing and editing mappings. You can map entity types or associations to

    database tables, columns, and stored procedures. For more information, seeMapping Details Window.

    A Model Browser window that provides tree views of the conceptual model and the storage model. For morinformation, see Model Browser Window.

    Toolbox controls for creating entities, associations, and inheritance relationships.

    The Entity Designer is integrated with Visual Studio components.

    The Entity Designer works with an .edmx file. An .edmx file is the combination of three EDM metadata files: the

    onceptual schema definition language (CSDL), store schma definition language (SSDL), and mapping spcificationanguage (MSL) files. When you run the Entity Data Model Wizard, an .edmx file is created and added to your

    olution. This file is automatically opened in the Entity Designer when the Entity Wizard finishes. You can also ope

    he .edmx file in the Entity Designer by double-clicking it in Solution Explorer.

    The following screenshot shows an .edmx file opened in the Entity Designer. The screenshot shows the visual designurface for creating and editing the conceptual model, the Model Browser window, and the Mapping Details wind

    http://msdn.microsoft.com/en-us/library/bb387165.aspxhttp://msdn.microsoft.com/en-us/library/bb387165.aspxhttp://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb738481.aspxhttp://msdn.microsoft.com/en-us/library/bb738481.aspxhttp://msdn.microsoft.com/en-us/library/bb738481.aspxhttp://msdn.microsoft.com/en-us/library/bb738483.aspxhttp://msdn.microsoft.com/en-us/library/bb738483.aspxhttp://msdn.microsoft.com/en-us/library/bb387165.aspxhttp://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb738481.aspxhttp://msdn.microsoft.com/en-us/library/bb738483.aspx
  • 8/3/2019 Introducing the Entity Framework

    5/21

    For detailed information about how to use the Entity Designer, seeEntity Data Model Tools Tasks.

    http://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspx
  • 8/3/2019 Introducing the Entity Framework

    6/21

    Entity Framework Features Not Supported by the

    Entity Designer

    The following are Entity Framework features that are not currently supported by the Entity Designer.

    Multiple entity sets per type.

    Creating entity sets for non-root types.

    Table-per-concrete class mapping.

    Using EntityType properties in mapping conditions.

    Editing storage model elements.

    Unmapped abstract types. When you create an abstract entity type with the Entity Designer, the type must bemapped to a table or view.

    Creating conditions on association mappings.

    Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. Y

    can indirectly map other associations to stored procedures along with entity types by mapping the appropriatnavigation properties to stored procedure parameters.

    Creating conditions on Function Import mappings.

    Complex types.

    Annotations.

    QueryViews.

    Specifying a parameter on an update function to return the number of rows affected. The Entity Designer do

    not expose a user interface for specifying this output parameter. However, you can manually edit the .edmx f

    so that the update function will handle this output parameter.

    Models that contain references to other models.

    NoteAttempting to use these features with the Entity Designer, or making manual edits to the .edmx file, might re

    in an error that stops the Entity Designer from displaying the .edmx file. In this case, you will be prompted toopen the file with the XML Editor.

    Generating an Entity Data Model

    Entity Framework applications and services are based on the Entity Data Model (EDM). This model representsapplication data as a set of entities and relationships that are mapped to a defined data source. An EDM consists of a

    onceptual model expressed as entities and relationships, a storage model that represents the schema of the logical

    model, and a mapping between the two. The development phase of a project usually starts with the conceptual modeand then the logical model is derived from the conceptual model.

    To meet the needs of developers who want to derive an Entity Data Model from an existing database, the Entity

    Framework provides a set of tools that generate an EDM, validate an EDM, and create programmable classes based

    he conceptual model. The EDM Generator (EdmGen.exe)command prompt utility enables you to generate a simplmodel with a one-to-one mapping between entities and tables in a data source. You can also use EdmGen.exe to

    http://msdn.microsoft.com/en-us/library/bb387165.aspxhttp://msdn.microsoft.com/en-us/library/bb387165.aspxhttp://msdn.microsoft.com/en-us/library/bb387165.aspx
  • 8/3/2019 Introducing the Entity Framework

    7/21

    generate the data classes that are based on entity types and to validate an EDM. EdmGen.exe is part of the Entity

    Framework runtime components in the .NET Framework 3.5 Service Pack 1(SP1).

    Visual Studio 2008 SP1 includes an integrated set of Entity Data Model tools that generates a model that includeselected objects from a data source. You can then modify the conceptual model and mapping using the Entity Data

    Model Designerto achieve the conceptual model that is required by the application. For more information, seeEntitData Model Tools.

    Considerations

    The following considerations apply when you generate an EDM:

    All entities are required to have keys. If the database has a table without a primary key, the EDM tools try to

    infer a key for the corresponding entity. In addition, the EDM tools generate a DefiningQuery element in the

    store schema that makes the data for this entity read-only. To make the entity data updatable, you must verif

    that the generated key is a valid key and then remove the DefiningQuery element. A table that represents a many-to-many relationship between two tables in the database may not have an

    equivalent entity in the conceptual schema. When the EDM tools encounter such a table with no columns oththan the two that are foreign keys, the mapping table is represented in the conceptual schema as a many-to-

    many association instead of an entity. The CourseInstructor association in the School model is an example

    this behavior. For more information, see Generating the School Entity Data Model (Entity FrameworkQuickstart).

    In this release, the Entity Data Model tools only support automatic generation of an EDM based on an existi

    data source. You cannot automatically generate a data source, such as a relational database, based on the

    conceptual model.

    The School ModelThe topics in this Getting Started section refer to a sample database named School. See Creating the School Sample

    Database (Entity Framework Quickstart) for the script that generates the School database on SQL Server.

    School contains the following tables:

    Course

    CourseGrade

    CourseInstructor

    Department OfficeAssignment

    OnlineCourse

    OnsiteCourse Person

    http://msdn.microsoft.com/en-us/library/cc716685.aspxhttp://msdn.microsoft.com/en-us/library/cc716685.aspxhttp://msdn.microsoft.com/en-us/library/bb399249.aspxhttp://msdn.microsoft.com/en-us/library/bb399249.aspxhttp://msdn.microsoft.com/en-us/library/bb399249.aspxhttp://msdn.microsoft.com/en-us/library/bb399249.aspxhttp://msdn.microsoft.com/en-us/library/bb738450.aspxhttp://msdn.microsoft.com/en-us/library/bb399739.aspxhttp://msdn.microsoft.com/en-us/library/bb399739.aspxhttp://msdn.microsoft.com/en-us/library/bb399731.aspxhttp://msdn.microsoft.com/en-us/library/bb399731.aspxhttp://msdn.microsoft.com/en-us/library/cc716685.aspxhttp://msdn.microsoft.com/en-us/library/cc716685.aspxhttp://msdn.microsoft.com/en-us/library/bb399249.aspxhttp://msdn.microsoft.com/en-us/library/bb399249.aspxhttp://msdn.microsoft.com/en-us/library/bb738450.aspxhttp://msdn.microsoft.com/en-us/library/bb399739.aspxhttp://msdn.microsoft.com/en-us/library/bb399739.aspxhttp://msdn.microsoft.com/en-us/library/bb399731.aspxhttp://msdn.microsoft.com/en-us/library/bb399731.aspx
  • 8/3/2019 Introducing the Entity Framework

    8/21

    This example database highlights many of the complex modeling scenarios supported by the Entity Data Model too

    The script creates the relationships between the tables and inserts sample data so that you can run the samples to see

    how they work. The following shows the School EDM displayed in the ADO.NET Entity Data Model Designer:

    Mapping a Conceptual Model to a Storage Schema

    The Entity Framework provides an object-centric view of tabular data, expressed as entity types. An application

    developer only has to think about programming against the object model that is generated from the conceptual mode

    ather than having to also think about the database schema and how to access database objects and transform them i

    programming objects. The Entity Framework uses model schemas and mappings to transform create, read, update, a

    delete operations against entities into equivalent operations in the data source.

    Note

    All the mapping file fragments that are shown in this section are generated by the EDM Generator (EdmGen.exe) to

    http://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb387165.aspxhttp://msdn.microsoft.com/en-us/library/bb738482.aspxhttp://msdn.microsoft.com/en-us/library/bb387165.aspx
  • 8/3/2019 Introducing the Entity Framework

    9/21

    The Conceptual Model

    The conceptual model is an Entity Data Model (EDM) schema that defines the entities and associations in the EDM

    The XML syntax that defines this model is called the conceptual schema definition language (CSDL). Entity types

    defined in CSDL each have a name, a key for uniquely identifying instances, and a set of properties. The data typesassigned to properties are specified as either simple types, which are scalar properties, or as complex types, which a

    ypes that consist of one or more scalar or complex properties. Additional properties may also specify nullability or

    assign a default value. Associations define the relationships between entities. Entity Framework language elements a

    erminology are explained in more detail in Entity Framework Terminology.

    The following XML fragment represents part of the conceptual model for the School EDM that defines the Course

    Department entity types that are related by the FK_Course_Department association, with other entities and

    associations removed.

    Copy Code...

    ...

    ......

  • 8/3/2019 Introducing the Entity Framework

    10/21

    Unicode="true" FixedLength="false" />...

    ...

    ...

    The Storage Model

    A separate data model uses store schema definition language (SSDL) to describe the logical model for persistent datusually stored in a relational database. The data types of properties declared in SSDL files are those of the storage

    model. This storage model fragment shows an example of storage metadata for the Course and Department tables

    he School database that are related by the FK_Course_Department foreign key, with other entities removed.

    Copy Code

    ...

    ...

    ...

  • 8/3/2019 Introducing the Entity Framework

    11/21

    ......

    ...

    The Mapping Specification

    A mapping specification uses mapping specification language (MSL) to connect the types declared in the conceptuamodel to the database metadata declared in the storage model. This MSL fragment demonstrates a one-to-one mapp

    between the conceptual and storage models for the Course and Department entities in the School model.

    Copy Code...

    ...

    ...

  • 8/3/2019 Introducing the Entity Framework

    12/21

    StoreEntitySet="Course">

    ...

    Discussion

    The School model that is discussed here uses a simple one-to-one mapping between a conceptual entity and a databaable but the Entity Framework supports more complex mappings. For example, the relational database might use m

    han one table to store data related to each employee. One table could contain contact information for all people and

    eparate related table could contain information that pertains only to employees. The Entity Framework enablesdevelopers to define entities using inheritance hierarchies and to map one entity to data from more than one table in

    database, with full support for data updates, inserts, and deletes. For more information, see Data Modeling in the En

    Framework.

    Working with Entity Data

    The Entity Framework compiles a set of conceptual and storage schemas, together with the mappings between themnto bidirectional pairs of Entity SQL statements called client views. These views drive query and update processing

    he runtime engine. The mapping compiler that generates the views can be invoked either at design time or at runtim

    when the first query is executed against an Entity Data Model (EDM) schema.

    The Entity Framework builds on top of storage-specific ADO.NET data providers by providing anEntityConnectionan underlying data provider and relational database.

    When a query is executed, it is parsed and converted into a canonical command tree, which is an object model

    epresentation of the query. Canonical command trees represent select, update, insert, and delete commands. Allubsequent processing is performed on the command tree, which is the means of communication between the

    System.Data.EntityClient provider and the underlying .NET Framework data provider, such asSystem.Data.SqlClie

    The following diagram illustrates the Entity Framework architecture for accessing data:

    http://msdn.microsoft.com/en-us/library/bb399183.aspxhttp://msdn.microsoft.com/en-us/library/bb399183.aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection.aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection.aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.aspxhttp://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspxhttp://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspxhttp://msdn.microsoft.com/en-us/library/bb399183.aspxhttp://msdn.microsoft.com/en-us/library/bb399183.aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection.aspxhttp://msdn.microsoft.com/en-us/library/system.data.entityclient.aspxhttp://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx
  • 8/3/2019 Introducing the Entity Framework

    13/21

    Querying Objects

    The Entity Framework tools generate a class derived from ObjectContextthat represents the entity container defined

    he conceptual model. The ObjectContext class supports queries against an EDM that return entities as objects, as was creating, updating, and deleting entity objects. The Entity Framework supports object queries against an EDM.

    Queries can be composed using Entity SQL, Language-Integrated Query (LINQ), and object query builder methods

    n a conceptual model, entities are related to each other by associations. In the object layer, these associations are

    epresented by properties that expose collections of related objects based on an entity reference. For example, in theSchool model, Department.Course gets an entity collection ofCourse objects based on the association between

    Course and Department. Because referenced objects are not automatically loaded, you must call the Load method

    he entity reference to load the related object data into the object context. You can also specify a query path that def

    which related objects to load with returned objects. For more information, seeQuerying Data as Objects (EntityFramework).

    The following example from the quickstartshows a query that, when executed, retrieves all Department objects. A

    query path definition ensures that the Course objects related to Department objects are also returned. An Entity SQORDER BY clause orders the returned objects by Name.

    http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspxhttp://msdn.microsoft.com/en-us/library/bb896375.aspxhttp://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspxhttp://msdn.microsoft.com/en-us/library/bb896375.aspxhttp://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspx
  • 8/3/2019 Introducing the Entity Framework

    14/21

    Visual Basic

    Copy Code Define a query that returns all Department objects and related Course objects, ordered by name.Dim departmentQuery As ObjectQuery(Of Department) = _

    schoolContext.Department.Include("Course").OrderBy("it.Name")C#

    Copy Code/ Define a query that returns all Department objects and related/ Course objects, ordered by name.ObjectQuery departmentQuery =

    schoolContext.Department.Include("Course").OrderBy("it.Name");

    For more information, see Querying Data as Objects (Entity Framework).

    You can define an EDM that uses stored procedures to execute queries at the data source. The result sets from these

    tored procedures are mapped to entities in the conceptual model. For more information, see Stored Procedure Supp

    Entity Framework).

    Working with Objects

    An object in an object context is an entity type representation of data in the data source. You can modify, create, anddelete objects in an object context. The object context manages identities and relationships between objects. You ca

    also serialize objects and bind objects to controls. For more information, see Working with Objects (Entity

    Framework).

    The following example from the quickstartgets a collection ofCourse objects related to a Department object and

    binds the collection to a DataGridView control.

    Visual Basic

    Copy Code Get the object for the selected department.Dim department As Department = _

    CType(Me.departmentList.SelectedItem, Department)

    Bind the grid view to the collection of Course objects that are related to the selected Department object.courseGridView.DataSource = department.Course

    C#

    Copy Code/ Get the object for the selected department.Department department =

    (Department)this.departmentList.SelectedItem;

    / Bind the grid view to the collection of Course objects/ that are related to the selected Department object.courseGridView.DataSource = department.Course;

    http://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb738470.aspxhttp://msdn.microsoft.com/en-us/library/bb738470.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb738642.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb738470.aspxhttp://msdn.microsoft.com/en-us/library/bb738470.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspx
  • 8/3/2019 Introducing the Entity Framework

    15/21

    The Entity Framework tracks changes to entity data and enables you to persist changes back to the data source. In th

    following example from the quickstart, changes in the object context are written to the database.

    Visual BasicCopy Code Save object changes to the database, display a message, and refresh the form.numChanges = schoolContext.SaveChanges()

    C#

    Copy Code/ Save object changes to the database, display a message,/ and refresh the form.numChanges = schoolContext.SaveChanges();

    For more information, see Adding, Modifying, and Deleting Objects (Entity Framework).

    You can define an EDM that uses stored procedures to insert, update, and delete data at the data source. These store

    procedures are mapped to entities in the conceptual model. For more information, seeStored Procedure Support (En

    Framework).

    Quickstart (Entity Framework)

    This quickstart illustrates a series of tasks that support the topics inGetting Started (Entity Framework). These tasks

    designed to help you become familiar with the ADO.NET Entity Framework.

    What You Will Learn

    The first task in this quickstart shows you how to create the School database, and then use Visual Studio tools to

    generate mapping files for an Entity Data Model (EDM), based on a 1:1 mapping to tables in the database. In

    ubsequent tasks, you will create a Windows Forms application in Visual Studio, create queries that access data in th

    School model, bind the query results to display controls to show the results of the queries, and then make updates toobjects and persist the changes to the database.

    You can download the completed Course Manager as both a Visual Basic project and a C# project from the MSDN

    Code Gallery Web site.

    http://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb386876.aspxhttp://msdn.microsoft.com/en-us/library/bb386876.aspxhttp://msdn.microsoft.com/en-us/library/bb386876.aspxhttp://go.microsoft.com/fwlink/?LinkId=91908http://go.microsoft.com/fwlink/?LinkId=91908http://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb738695.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb399203.aspxhttp://msdn.microsoft.com/en-us/library/bb386876.aspxhttp://go.microsoft.com/fwlink/?LinkId=91908http://go.microsoft.com/fwlink/?LinkId=91908
  • 8/3/2019 Introducing the Entity Framework

    16/21

    Requirements

    This quickstart is intended for users who are familiar with Visual Studio development and the .NET Framework, buwho are new to the Entity Framework. To complete the quickstart, you must have the following software installed:

    Microsoft Visual Studio 2008.

    The ADO.NET Entity Framework runtime and tools. You can download the ADO.NET Entity Framework

    runtime and tools from the Microsoft Download Center.

    Microsoft SQL Server 2005 or later with Database Services, or the Express edition of SQL Server 2005 or la

    Estimated time to complete this tutorial: 30 minutes.

    How to: Create a New Entity Data ModelThis topic describes how to create a new Entity Data Model (EDM) by using the Entity Data Model Wizard. The

    procedures in this topic describe how to generate a model that is based on an existing database (this is recommendedfor this version of the ADO.NET Entity Data Model Designer), and how to generate an empty model.

    Note

    You typically generate an empty model when you want to model the data for an application before you design the

    torage schema. Modeling data first requires deploying the application with a data source that fits the model.

    An EDM can be included in the following Visual Studio project categories:

    Application projects Class libraries

    Web projects

    Multiple EDMs can be added to the same project, and each EDM can target a different database, different tables in tame database, or both.

    To create an EDM from an existing database

    1. Open or create the project for which you want to create an EDM.2. Right-click the project name in Solution Explorer, point to Add, and then clickNew Item.3. Select ADO.NET Entity Data Model in the Templates pane.

    4. Enter the name for the model (.edmx), and then clickAdd.

    The first page of the Entity Data Model Wizard appears.

    5. Select Generate from database in the Choose Model Contents dialog box, and then clickNext.

    http://go.microsoft.com/fwlink/?LinkId=95662http://go.microsoft.com/fwlink/?LinkId=95662http://go.microsoft.com/fwlink/?LinkId=95662
  • 8/3/2019 Introducing the Entity Framework

    17/21

    6. Click the New Connection button.

    The Connection Properties dialog box appears.

    7. Enter the server name, select the authentication method, and enter the name of the database for which the mo

    is being created. ClickOK.

    The Choose Your Data Connections dialog box is updated with the database connection settings.

    Note

    By default, entity connection settings are saved in the App.config or Web.config file (depending on the proje

    type). Type a name for the connection or use the provided default name. Clear the Save entity connection

    settings check box if you do not want connection information saved in a configuration file. For more

    information about saving connection settings, see Choose Your Data Connection Dialog Box.

    8. Click Next to continue.

    The Choose Your Database Objects dialog box appears. By default, no objects in the database are selected

    inclusion in the EDM.

    9. Expand the nodes for Tables, Views, and Stored Procedures. Cancel the selection of any tables, views, andstored procedures that you do not want included in the model.

    Note

    Classes generated from the conceptual model will be in the Model Namespace. Type a name for the namespor use the provided default name.

    10. ClickFinish to create the EDM.

    The Entity Data Model Wizard does the following:

    o Adds references to the System.Data, System.Data.Entity, System.Core, System.Security, and

    System.Runtime.Serialization assemblies to the project, if they do not already exist.o Generates an .edmx file that encapsulates the storage model, the conceptual model, and mappings.

    o Creates a source code file that contains classes generated from the conceptual model. You can view t

    source code file by expanding the .edmx node in Solution Explorer. To see the source code file inVisual Basic projects, you must click the Show All Files button in Solution Explorer before you

    expand the .edmx node.

    Note

    The source code file is generated from the .edmx file. Any manual changes to the source code file are

    overwritten when the corresponding .edmx file changes. To prevent custom code from being overwritten, yocan write partial classes that are stored in separate files. For more information, seeCustomizing Objects (EntFramework).

    o Creates an App.Config or Web.Config file (depending on the project type).

    o For ASP.NET Website projects, defines a build provider in the Web.config file.

    o Displays the EDM in the ADO.NET Entity Data Model Designer (Entity Designer). For information

    about how to modify your model with the Entity Designer, see Entity Data Model Tools Tasks and

    ADO.NET Entity Data Model Designer Scenarios.

    http://msdn.microsoft.com/en-us/library/bb399244.aspxhttp://msdn.microsoft.com/en-us/library/bb738612.aspxhttp://msdn.microsoft.com/en-us/library/bb738612.aspxhttp://msdn.microsoft.com/en-us/library/bb738612.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/cc716693.aspxhttp://msdn.microsoft.com/en-us/library/bb399244.aspxhttp://msdn.microsoft.com/en-us/library/bb738612.aspxhttp://msdn.microsoft.com/en-us/library/bb738612.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/cc716693.aspx
  • 8/3/2019 Introducing the Entity Framework

    18/21

    For an example of creating an actual model from an existing database, seeQuickstart (Entity Framework).

    To create an empty model

    1. Open or create the project for which you want to create an EDM.2. Right-click the project name in Solution Explorer, point to Add, and then clickNew Item.

    3. Select ADO.NET Entity Data Model in the Templates pane.

    4. Enter the name for the model (.edmx), and then clickAdd.

    The first page of the Entity Data Model Wizard appears.

    5. Select Empty Model in the Choose Model Contents dialog box, and then clickFinish.

    The Entity Data Model Wizard does the following:

    o Adds references to the System.Data, System.Data.Entity, System.Core, System.Security, andSystem.Runtime.Serialization assemblies to the project, if they do not already exist.o Generates an .edmx file to encapsulate the storage model, the conceptual model, and mappings.

    Note

    The generated .edmx file has no storage, conceptual, or mapping information. For information about how to

    to your model by modifying this file, seeEntity Data Model, EDM Specifications, and Schemas and MappinSpecification (Entity Framework).

    o Creates an empty source code file to contain classes that are generated from the conceptual model. Y

    can view the source code file by expanding the .edmx node in Solution Explorer. To see the sourcecode file in Visual Basic projects, you must click the Show All Files button in Solution Explorer be

    you expand the .edmx node.

    NoteThe source code file is generated from the .edmx file. Any manual changes to the source code file are

    overwritten when the corresponding .edmx file changes.

    o Creates an App.Config or Web.Config file (depending on the project type).

    o Starts the Entity Designer, which provides a design surface for editing your model. For information

    about how to build your model with the Entity Designer, see Entity Data Model Tools Tasks and

    ADO.NET Entity Data Model Designer Scenarios.

    How to: Add an Existing Entity Data Model

    This topic describes how to add an existing Entity Data Model (EDM) to a Visual Studio project. To add an existingEDM to a project, you add an existing .edmx file to the project. The .edmx file contains storage, conceptual, and

    mapping information for the model.

    Note

    The procedure outlined in this topic assumes that the database already exists (or will be created) for the model being

    dded.

    http://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb387122.aspxhttp://msdn.microsoft.com/en-us/library/bb387122.aspxhttp://msdn.microsoft.com/en-us/library/bb399281.aspxhttp://msdn.microsoft.com/en-us/library/bb399604.aspxhttp://msdn.microsoft.com/en-us/library/bb399604.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/cc716693.aspxhttp://msdn.microsoft.com/en-us/library/bb399182.aspxhttp://msdn.microsoft.com/en-us/library/bb387122.aspxhttp://msdn.microsoft.com/en-us/library/bb399281.aspxhttp://msdn.microsoft.com/en-us/library/bb399604.aspxhttp://msdn.microsoft.com/en-us/library/bb399604.aspxhttp://msdn.microsoft.com/en-us/library/bb738480.aspxhttp://msdn.microsoft.com/en-us/library/cc716693.aspx
  • 8/3/2019 Introducing the Entity Framework

    19/21

    To add an existing EDM to a Visual Studio Project

    1. Open or create the project to which you want to add an existing EDM.2. Right-click the project name in Solution Explorer, point to Add, and then clickExisting Item.

    The Add Existing Item dialog box appears.

    3. Browse to the .edmx file that corresponds to model being added.

    4. Select the .edmx file to be added, and then clickAdd.

    The .edmx file is added to the project. The following are also added to the project:

    o References to the System.Data, System.Data.Entity, System.Core, System.Security, and

    System.Runtime.Serialization assemblies, if they do not already exist.o A source code file that contains classes that were generated from the conceptual model. You can view

    the source code file by expanding the .edmx node in Solution Explorer.Note

    The source code file is generated from the .edmx file. Any manual changes to the source code file are

    overwritten when the corresponding .edmx file changes.

    Note

    In Visual Basic projects, you must click the Show All Files button in Solution Explorer to see the source co

    file.

    5. Add the connection string to the App.Config or Web.Config file, depending on the project type.

    For information about connection string format, see Connection Strings (Entity Framework)and How to:Define the Connection String (Entity Framework).

    If your project does not already contain an App.Config or Web.Config file, you can add one by following th

    steps:

    . Right-click the project name in Solution Explorer, point to Add, and then clickNew Item.

    The Add New Item dialog box appears.

    . Select Application Configuration File or Web Configuration File, depending on the project type.

    . ClickAdd.

    How to: Map Entities to Database Tables

    This topic describes how to map an entity type to a database table by using the ADO.NET Entity Data Model DesigEntity Designer). The Mapping Details window enables you map an entity to one or more tables, define condition

    for the mapping, and specify the column to property mappings.

    Note

    http://msdn.microsoft.com/en-us/library/cc716756.aspxhttp://msdn.microsoft.com/en-us/library/cc716756.aspxhttp://msdn.microsoft.com/en-us/library/bb896291.aspxhttp://msdn.microsoft.com/en-us/library/bb896291.aspxhttp://msdn.microsoft.com/en-us/library/cc716756.aspxhttp://msdn.microsoft.com/en-us/library/bb896291.aspxhttp://msdn.microsoft.com/en-us/library/bb896291.aspx
  • 8/3/2019 Introducing the Entity Framework

    20/21

    This topic focuses on how to map an entity type to a single database table. However, an entity type can be mapped to

    multiple database tables. For an example of how to do this, see Walkthrough: Mapping an Entity to Multiple Tables

    The following table describes the fields in the Mapping Details window when an entity type is selected on the desig

    urface.

    Name Description

    Column Contains an alphabetized list of all columns in the table.

    Operator Shows the mapping or condition operator.

    Value/Property

    Displays the entity property that is mapped to the column.

    If the field is blank, this means that the column is currently not mapped to a scalar property.

    When you click the field, it becomes a drop-down list that displays all the scalar properties.

    To add a mapping1. Right-click an entity type on the design surface or in the Model Browser and select Table Mappings.

    The table mappings are displayed in the Mapping Details window.

    2. In the Mapping Details window, clickAdd a Table or View.

    The field becomes a drop-down list that contains all the tables in the storage model that are not already inclu

    in the current mapping.

    3. Select a table from the list.

    A Maps to node is added to the window. This node contains default mappings between tabl

    columns and entity properties.The wizard checks whether column names match property names. If they matcthe default mapping is between the column and property of the same name.

    An additional Add a Table or View row appears underneath the new mapping node. This enables you to ad

    another table to the mapping.

    4. Expand the Maps to node.

    You can use the Add a Condition option to add a condition. Conditions enable the mapping system to map particular type in the hierarchy to or from rows in a table, based on the values of the selected condition colum

    Entity types can define a set of conditions for each table to which they are mapped. For more information, se

    How to: Add or Delete Conditions.

    A Column Mappings node also appears.

    5. Expand the Column Mappings node.

    http://msdn.microsoft.com/en-us/library/cc716698.aspxhttp://msdn.microsoft.com/en-us/library/bb738484.aspxhttp://msdn.microsoft.com/en-us/library/cc716698.aspxhttp://msdn.microsoft.com/en-us/library/bb738484.aspx
  • 8/3/2019 Introducing the Entity Framework

    21/21

    A list of all the columns in the table appears. The default properties (if any) to which the columns map are li

    under the Value/Property heading.

    6. Select the column you want to map, and then right-click the corresponding Value/Property field.

    A drop-down list of all the scalar properties is displayed.

    7. Select the appropriate property.8. Repeat steps 6 and 7 for each table column.

    To delete a table mapping

    1. Click the Maps to node.

    The field becomes a drop-down list.

    2. Select Delete.

    To delete a column mapping

    1. Select the column that you want to map, and then click the Value/Property field.

    The field becomes a drop-down list.

    2. Select Delete.