Você está na página 1de 21

Introducing the Entity Framework

The Entity Framework is a set of technologies in ADO.NET that support development of data-oriented software applications. Architects and developers of data-oriented applications have struggled with the need to achieve two very 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 storage systems, each with its own protocols; even applications that work with a single storage system must balance the requirements 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, such as customers and customer addresses, without having to concern themselves with the underlying database tables and 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 applications. Because the Entity Framework is a component of the .NET Framework, Entity Framework applications can run on any computer 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 conceptual model, a logical model, and a physical model. The conceptual model defines the entities and relationships in the system that is being modeled. The logical model for a relational database normalizes the entities and relationships into tables with foreign key constraints. The physical model addresses the capabilities of a particular data engine by specifying storage details such as partitioning and indexing. The physical model is refined by database administrators to improve performance, but programmers writing application code primarily confine themselves to working with the logical model by writing SQL queries and calling stored procedures. 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 then abandoned. Many development teams skip creating a conceptual model and begin by specifying tables, columns, and keys in a relational database. The Entity Framework gives life to conceptual models by enabling developers to query entities and relationships in the conceptual model while relying on the Entity Framework to translate those operations to data source-specific commands. This frees applications from hard-coded dependencies on a particular data source. The conceptual model, the 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 conceptual model, data classes, or application code. Because storage models are provider-specific, you can work with a consistent 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 model. Mapping specification language file (.msl) - defines the mapping between the storage and conceptual models.

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 more information, see Data Modeling in the Entity Framework.

Mapping Objects to Data


Object-oriented programming poses a challenge for interacting with data storage systems. Although the organization of classes 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 differently 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 contains a foreign key column (or set of columns) with a value that corresponds to a primary key value in the Customer table. A Customer class might have a property named Orders that contains a collection of instances of the Order class, but the 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 mapping object-oriented classes and properties to relational tables and columns. Instead of taking this traditional approach, the Entity Framework maps relational tables, columns, and foreign key constraints in logical models to entities and relationships in conceptual models. This enables greater flexibility both in defining objects and optimizing the logical model. The Entity Data Model tools generate extensible data classes based on the conceptual model. These classes are partial classes that can be extended with additional members that the developer adds. The classes that are generated for a particular conceptual model derive from base classes that provide Object Services for materializing entities as objects and 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. Object Services uses the EDM to translate object queries against entity types that are represented in the conceptual model into data 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 and that supports EDM features such as inheritance and relationships. Entity SQL is used both with object queries and queries that are executed by using the EntityClient provider. For more information, see Entity SQL Overview. Query builder methods - enables you to construct Entity SQL queries using LINQ-style query methods. For more information, see Query Builder Methods (Entity Framework).

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 data into objects. When object materialization is not required, the EntityClient provider can also be used like a standard ADO.NET data provider by enabling applications to execute Entity SQL queries and consume the returned read-only 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 from ObjectContext that represents the entity container in the conceptual model. This object context provides the facilities for tracking changes and managing identities, concurrency, and relationships. This class also exposes a SaveChanges method that writes inserts, updates, and deletes to the data source. Like queries, these changes are either made by commands automatically generated by the system or by stored procedures that are specified by the developer. For more information, see Adding, Modifying, and Deleting 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 between

entities and tables. It also uses a conceptual model file (.csdl) to generate an object layer file that contains classes that represent 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 application. The Entity Data Model Designer supports creating advanced mapping scenarios, such as table-per-type and table-perhierarchy inheritance and split entities that map to multiple tables. For more information, see ADO.NET Entity Data Model 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 modification of an EDM. You can use the Entity Designer to visually create and modify entities, associations, mappings, and inheritance 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, see Mapping Details Window. A Model Browser window that provides tree views of the conceptual model and the storage model. For more information, 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 conceptual schema definition language (CSDL), store schma definition language (SSDL), and mapping spcification language (MSL) files. When you run the Entity Data Model Wizard, an .edmx file is created and added to your solution. This file is automatically opened in the Entity Designer when the Entity Wizard finishes. You can also open the .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 design surface for creating and editing the conceptual model, the Model Browser window, and the Mapping Details window.

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

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 be mapped to a table or view. Creating conditions on association mappings. Mapping associations directly to stored procedures. Mapping many-to-many associations is not supported. You can indirectly map other associations to stored procedures along with entity types by mapping the appropriate navigation 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 does not expose a user interface for specifying this output parameter. However, you can manually edit the .edmx file so that the update function will handle this output parameter. Models that contain references to other models. Note Attempting to use these features with the Entity Designer, or making manual edits to the .edmx file, might result in an error that stops the Entity Designer from displaying the .edmx file. In this case, you will be prompted to open 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 represents application data as a set of entities and relationships that are mapped to a defined data source. An EDM consists of a conceptual 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 model, and 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 on the conceptual model. The EDM Generator (EdmGen.exe) command prompt utility enables you to generate a simple model with a one-to-one mapping between entities and tables in a data source. You can also use EdmGen.exe to

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 includes selected objects from a data source. You can then modify the conceptual model and mapping using the Entity Data Model Designer to achieve the conceptual model that is required by the application. For more information, see Entity Data 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 verify 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 other than the two that are foreign keys, the mapping table is represented in the conceptual schema as a many-tomany association instead of an entity. The CourseInstructor association in the School model is an example of this behavior. For more information, see Generating the School Entity Data Model (Entity Framework Quickstart). In this release, the Entity Data Model tools only support automatic generation of an EDM based on an existing data source. You cannot automatically generate a data source, such as a relational database, based on the conceptual model.

The School Model


The 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

This example database highlights many of the complex modeling scenarios supported by the Entity Data Model tools. 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 model, rather than having to also think about the database schema and how to access database objects and transform them into programming objects. The Entity Framework uses model schemas and mappings to transform create, read, update, and 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) tool.

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 types assigned to properties are specified as either simple types, which are scalar properties, or as complex types, which are types 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 and terminology 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 and Department entity types that are related by the FK_Course_Department association, with other entities and associations removed. Copy Code
<?xml version="1.0" encoding="utf-8"?> <Schema Namespace="SchoolModel" Alias="Self" xmlns="http://schemas.microsoft.com/ado/2006/04/edm"> <EntityContainer Name="SchoolEntities"> <EntitySet Name="Course" EntityType="SchoolModel.Course" /> <EntitySet Name="Department" EntityType="SchoolModel.Department" /> ... <AssociationSet Name="FK_Course_Department" Association="SchoolModel.FK_Course_Department"> <End Role="Department" EntitySet="Department" /> <End Role="Course" EntitySet="Course" /> </AssociationSet> ... </EntityContainer> <EntityType Name="Course"> <Key> <PropertyRef Name="CourseID" /> </Key> <Property Name="CourseID" Type="Int32" Nullable="false" /> <Property Name="Title" Type="String" Nullable="false" MaxLength="100" Unicode="true" FixedLength="false" /> ... <NavigationProperty Name="Department" Relationship="SchoolModel.FK_Course_Department" FromRole="Course" ToRole="Department" /> ... </EntityType> <EntityType Name="Department"> <Key> <PropertyRef Name="DepartmentID" /> </Key> <Property Name="DepartmentID" Type="Int32" Nullable="false" /> <Property Name="Name" Type="String" Nullable="false" MaxLength="50"

Unicode="true" FixedLength="false" /> ... <NavigationProperty Name="Course" Relationship="SchoolModel.FK_Course_Department" FromRole="Department" ToRole="Course" /> </EntityType> ... <Association Name="FK_Course_Department"> <End Role="Department" Type="SchoolModel.Department" Multiplicity="1" /> <End Role="Course" Type="SchoolModel.Course" Multiplicity="*" /> </Association> ... </Schema>

The Storage Model


A separate data model uses store schema definition language (SSDL) to describe the logical model for persistent data, usually 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 in the School database that are related by the FK_Course_Department foreign key, with other entities removed. Copy Code
<?xml version="1.0" encoding="utf-8"?> <Schema Namespace="SchoolModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl"> <EntityContainer Name="dbo"> <EntitySet Name="Course" EntityType="SchoolModel.Store.Course" store:Type="Tables" /> <EntitySet Name="Department" EntityType="SchoolModel.Store.Department" store:Type="Tables" /> ... <AssociationSet Name="FK_Course_Department" Association="SchoolModel.Store.FK_Course_Department"> <End Role="Department" EntitySet="Department" /> <End Role="Course" EntitySet="Course" /> </AssociationSet> ... </EntityContainer> <EntityType Name="Course"> <Key> <PropertyRef Name="CourseID" /> </Key> <Property Name="CourseID" Type="int" Nullable="false" /> <Property Name="Title" Type="nvarchar" Nullable="false" MaxLength="100" /> ... </EntityType> <EntityType Name="Department"> <Key> <PropertyRef Name="DepartmentID" /> </Key> <Property Name="DepartmentID" Type="int" Nullable="false" />

<Property Name="Name" Type="nvarchar" Nullable="false" MaxLength="50" /> ... </EntityType> ... <Association Name="FK_Course_Department"> <End Role="Department" Type="SchoolModel.Store.Department" Multiplicity="1" /> <End Role="Course" Type="SchoolModel.Store.Course" Multiplicity="*" /> <ReferentialConstraint> <Principal Role="Department"> <PropertyRef Name="DepartmentID" /> </Principal> <Dependent Role="Course"> <PropertyRef Name="CourseID" /> </Dependent> </ReferentialConstraint> </Association> ... </Schema>

The Mapping Specification


A mapping specification uses mapping specification language (MSL) to connect the types declared in the conceptual model to the database metadata declared in the storage model. This MSL fragment demonstrates a one-to-one mapping between the conceptual and storage models for the Course and Department entities in the School model. Copy Code
<?xml version="1.0" encoding="utf-8"?> <Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS"> <EntityContainerMapping StorageEntityContainer="dbo" CdmEntityContainer="SchoolEntities"> <EntitySetMapping Name="Course"> <EntityTypeMapping TypeName="IsTypeOf(SchoolModel.Course)"> <MappingFragment StoreEntitySet="Course"> <ScalarProperty Name="CourseID" ColumnName="CourseID" /> <ScalarProperty Name="Title" ColumnName="Title" /> ... </MappingFragment> </EntityTypeMapping> </EntitySetMapping> <EntitySetMapping Name="Department"> <EntityTypeMapping TypeName="IsTypeOf(SchoolModel.Department)"> <MappingFragment StoreEntitySet="Department"> <ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" /> <ScalarProperty Name="Name" ColumnName="Name" /> ... </MappingFragment> </EntityTypeMapping> </EntitySetMapping> ... <AssociationSetMapping Name="FK_Course_Department" TypeName="SchoolModel.FK_Course_Department"

StoreEntitySet="Course"> <EndProperty Name="Department"> <ScalarProperty Name="DepartmentID" ColumnName="DepartmentID" /> </EndProperty> <EndProperty Name="Course"> <ScalarProperty Name="CourseID" ColumnName="CourseID" /> </EndProperty> <Condition ColumnName="DepartmentID" IsNull="false" /> </AssociationSetMapping> ... </cs:EntityContainerMapping> </Mapping>

Discussion
The School model that is discussed here uses a simple one-to-one mapping between a conceptual entity and a database table but the Entity Framework supports more complex mappings. For example, the relational database might use more than one table to store data related to each employee. One table could contain contact information for all people and a separate related table could contain information that pertains only to employees. The Entity Framework enables developers to define entities using inheritance hierarchies and to map one entity to data from more than one table in a database, with full support for data updates, inserts, and deletes. For more information, see Data Modeling in the Entity Framework. Working with Entity Data The Entity Framework compiles a set of conceptual and storage schemas, together with the mappings between them, into bidirectional pairs of Entity SQL statements called client views. These views drive query and update processing in the runtime engine. The mapping compiler that generates the views can be invoked either at design time or at runtime 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 an EntityConnection to an 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 representation of the query. Canonical command trees represent select, update, insert, and delete commands. All subsequent 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 as System.Data.SqlClient.

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

Querying Objects
The Entity Framework tools generate a class derived from ObjectContext that represents the entity container defined in the conceptual model. The ObjectContext class supports queries against an EDM that return entities as objects, as well as 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. In a conceptual model, entities are related to each other by associations. In the object layer, these associations are represented by properties that expose collections of related objects based on an entity reference. For example, in the School model, Department.Course gets an entity collection of Course objects based on the association between Course and Department. Because referenced objects are not automatically loaded, you must call the Load method on the entity reference to load the related object data into the object context. You can also specify a query path that defines which related objects to load with returned objects. For more information, see Querying Data as Objects (Entity Framework). The following example from the quickstart shows 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 SQL ORDER BY clause orders the returned objects by Name.

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<Department> 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 stored procedures are mapped to entities in the conceptual model. For more information, see Stored Procedure Support (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, and delete objects in an object context. The object context manages identities and relationships between objects. You can also serialize objects and bind objects to controls. For more information, see Working with Objects (Entity Framework). The following example from the quickstart gets a collection of Course 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;

The Entity Framework tracks changes to entity data and enables you to persist changes back to the data source. In the following example from the quickstart, changes in the object context are written to the database. Visual Basic Copy 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 stored procedures are mapped to entities in the conceptual model. For more information, see Stored Procedure Support (Entity Framework). Quickstart (Entity Framework) This quickstart illustrates a series of tasks that support the topics in Getting Started (Entity Framework). These tasks are 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 subsequent tasks, you will create a Windows Forms application in Visual Studio, create queries that access data in the School model, bind the query results to display controls to show the results of the queries, and then make updates to objects 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.

Requirements
This quickstart is intended for users who are familiar with Visual Studio development and the .NET Framework, but who 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 later.

Estimated time to complete this tutorial: 30 minutes.

How to: Create a New Entity Data Model


This 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 recommended for 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 storage 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 the same database, or both.

To create an EDM from an existing database


1. 2. 3. 4. Open or create the project for which you want to create an EDM. Right-click the project name in Solution Explorer, point to Add, and then click New Item. Select ADO.NET Entity Data Model in the Templates pane. Enter the name for the model (<project name>.edmx), and then click Add. The first page of the Entity Data Model Wizard appears. 5. Select Generate from database in the Choose Model Contents dialog box, and then click Next.

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 model is being created. Click OK. 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 project 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 for inclusion in the EDM. 9. Expand the nodes for Tables, Views, and Stored Procedures. Cancel the selection of any tables, views, and stored 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 namespace or use the provided default name. 10. Click Finish to create the EDM. The Entity Data Model Wizard does the following: 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 the source code file by expanding the .edmx node in Solution Explorer. To see the source code file in Visual 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, you can write partial classes that are stored in separate files. For more information, see Customizing Objects (Entity Framework). 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.
o

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

To create an empty model


1. 2. 3. 4. Open or create the project for which you want to create an EDM. Right-click the project name in Solution Explorer, point to Add, and then click New Item. Select ADO.NET Entity Data Model in the Templates pane. Enter the name for the model (<project name>.edmx), and then click Add. The first page of the Entity Data Model Wizard appears. 5. Select Empty Model in the Choose Model Contents dialog box, and then click Finish. The Entity Data Model Wizard does the following: 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 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 add to your model by modifying this file, see Entity Data Model, EDM Specifications, and Schemas and Mapping Specification (Entity Framework). o Creates an empty source code file to contain classes that are generated from the conceptual model. You can view the source code file by expanding the .edmx node in Solution Explorer. To see the source code file in Visual 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. 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.
o

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 existing EDM 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 added.

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 click Existing 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 click Add. The .edmx file is added to the project. The following are also added to the project: 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 code file. 5. Add the connection string to the App.Config or Web.Config file, depending on the project type.
o

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 these steps:
1.

Right-click the project name in Solution Explorer, point to Add, and then click New Item. The Add New Item dialog box appears.

2. 3.

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

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 Designer (Entity Designer). The Mapping Details window enables you map an entity to one or more tables, define conditions for the mapping, and specify the column to property mappings. Note

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 design surface. Name Column Operator Description Contains an alphabetized list of all columns in the table. Shows the mapping or condition operator. Displays the entity property that is mapped to the column.

Value/Property 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 mapping
1. 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, click Add a Table or View. The field becomes a drop-down list that contains all the tables in the storage model that are not already included in the current mapping. 3. Select a table from the list. A Maps to <Table Name> node is added to the window. This node contains default mappings between table columns and entity properties.The wizard checks whether column names match property names. If they match, the 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 add another table to the mapping. 4. Expand the Maps to <Table Name> node. You can use the Add a Condition option to add a condition. Conditions enable the mapping system to map a particular type in the hierarchy to or from rows in a table, based on the values of the selected condition columns. Entity types can define a set of conditions for each table to which they are mapped. For more information, see How to: Add or Delete Conditions. A Column Mappings node also appears. 5. Expand the Column Mappings node.

A list of all the columns in the table appears. The default properties (if any) to which the columns map are listed 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 <Table Name> 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.

Você também pode gostar