Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
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.
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).
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.
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.
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.
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>
<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>
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.
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).
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.
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.
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.
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).
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.
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.