Entity Framework Learning Summary: Overview of the ADO Entity Framework

Source: Internet
Author: User

Http://www.cnblogs.com/xlovey/archive/2011/01/03/1924800.html

ADO Entity Framework Overview

ADO in the new version features the new Entity Framework. It enables developers to focus on data through the object model, rather than the logical/relational data model. The Entity Framework helps abstract the logical data schema into a conceptual model and allows interaction with the conceptual model through object Services and new data providers named "EntityClient" in a variety of ways.

The Entity Framework abstracts the logical database structure using the conceptual layer (conceptualmodels), the mapping Layer (Mappings), and the logical layer (storagemodels). An alternative to EntityClient is Object service. Specifically, Object Services in the Entity Framework help reduce the number of data access code that developers need to write.

Entity Framework Components

The Entity Framework enables developers to write less data access code, reduce maintenance, abstract data structures into a more business-friendly way, and facilitate the persistence of data. When used in conjunction with LINQ to Entities, it also helps to reduce the number of compile-time errors because the Entity Framework generates strongly typed classes from the conceptual model.

The Entity Framework generates a conceptual model by which developers can write code. Using a new data provider named "EntityClient" and a new language called "Entity SQL" (similar to T-SQL), you can interact directly with the model. The EntityClient has a model similar to the familiar ADO, using EntityConnection and EntityCommand objects to return DbDataReader. Another way for developers to use Object Services is through a ObjectQuery object with entity SQL or LINQ to Entities. Object Services enable developers to take advantage of the generated classes of the conceptual model, which provide attributes such as strongly typed objects and persistence (see Figure 1).

Figure 1 Entity Framework Overview

These data access technologies enable developers to interact with the conceptual entities of the EDM. Each layer of the EDM exists as an XML file, and you can now use the command-line tool (Edmgen) manually (or by using the wizard in Visual Studio). EXE) to generate an EDM.

Entity Data Model

The core of the Entity Framework is in its model. The Entity Framework supports a logical storage model that represents a relational schema in a database. Relational databases typically store data in a way that differs from how the application uses the data. Typically, this forces developers to retrieve data according to the structure of the database that contains the data. As a result, developers typically load data into business entities that are more appropriate to handle business rules. In this example, the logical model represents the schema of the relational database, and the business entity represents the conceptual model. The Entity Framework uses a mapping layer to build bridges between models. Therefore, there are three active layers in the model of the Entity Framework:

· Concept Layer

· Mapping layer

· Logical layer

These three layers allow data to be mapped from relational databases to more object-oriented business models. The Entity Framework provides methods for defining these layers using XML files. It also generates a series of classes based on the schema of the conceptual model. These classes can be programmed to interact directly with the data. This provides an abstraction level so that developers can program against a conceptual model rather than a relational model. The Entity Framework maps all the commands that encode the conceptual model into the logical model (see Figure 2).

Figure 2 Designing the Entity Data Model (click the image for a larger view)

The conceptual model is defined in the XML file using the conceptual schema definition language (CSDL). The CSDL defines the entities and relationships that are known to the business layer of the application. The logical Model (representing the database schema) is defined in the XML file using the storage schema definition language (SSDL). For example, you might have an entity in the conceptual model that actually derives its data from multiple tables in a database. A conceptual model and a logical model can correlate entities in a one-to-one relationship. However, the function of the EDM is that it does not have to link entities in a one-way manner. The mapping layer (which is defined using the Mapping schema Language (MSL)) implements the mapping between the other two layers. This mapping enables developers to write code for the conceptual model and map these directives to the logical model.

Generating the Entity Data model

The database can be generated as a starting point for the EDM. You can then manually modify the XML (or you might use the model tools that may be available in future versions of Visual Studio). After you add the ADO EDM to your project, the wizard guides you through the process of creating the EDM.

The first step is to create the solution "Entityframeworktest" and the console Application "EFPROJECTCA".

Step Two, add "ADO." NET Entity Data Model ", named" NORTHWINDEF.EDMX ".

Then select "Generate From Database" and select "Empty model" if you are using POCO development mode later.

The creation was successful here. NORTHWINDEF.EDMX contains CSDL, SSDL, MSL, we can view its structure through Notepad, or we can copy it, change the extension to XML, and open it in VS2010.

Analysis CSDL

The metadata residing in the CSDL file contains a series of entities and relationships, where the entity is represented by the EntityType element and the relationship is represented by the association element. An entity contains a series of scalar attributes that define an entity. The key property indicates a property that is critical to the entity. Compound keywords are represented by separating each property name with a space. An entity can also contain a special type of property named "NavigationProperty." This defines how you can navigate from one entity to another entity by association.

<entitytype name= "Customers" >

<Key>

<propertyref name= "CustomerID"/>

</Key>

<property name= "CustomerID" type= "String" nullable= "false" Maxlength= "5" unicode= "true" fixedlength= "true"/>

<property name= "CompanyName" type= "String" nullable= "false" maxlength= "+" unicode= "true" Fixedlength= "false"/ >

<property name= "ContactName" type= "String" maxlength= "" "Unicode=" true "Fixedlength=" false "/>

...

<navigationproperty name= "Orders" relationship= "Northwindmodel.fk_orders_customers" fromrole= "Customers" ToRole = "Orders"/>

<navigationproperty name= "Customerdemographics" relationship= "Northwindmodel.customercustomerdemo" FromRole= " Customers "torole=" Customerdemographics "/>

</EntityType>

The following CSDL fragment defines the associationset between the Customer and its Orders:

<associationset name= "FK_Orders_Customers" association= "Northwindmodel.fk_orders_customers" >

<end role= "Customers" entityset= "Customers"/>

<end role= "Orders" entityset= "Orders"/>

</AssociationSet>

The End element of the AssociationSet represents the associated contributor. In this example, a Customers entity is associated with an Orders entity. Depending on the multiplicity definition, a Customers entity can also be associated with any number of orders entities.

The EntityType and association elements define the types of domain entities and relationships, while EntitySet and AssociationSet elements define the scope of entities and relationships. All "sets" that logically should be grouped together are contained within the EntityContainer element.

The following CSDL fragment shows EntityContainer and some of its contents:

<entitycontainer name= "NorthwindEntities" annotation:lazyloadingenabled= "true" >

<entityset name= "Categories" entitytype= "Northwindmodel.categories"/>

<entityset name= "Customerdemographics" entitytype= "Northwindmodel.customerdemographics"/>

<entityset name= "Customers" entitytype= "Northwindmodel.customers"/>

...

<associationset name= "fk_products_categories" association= "Northwindmodel.fk_products_categories" >

<end role= "Categories" entityset= "Categories"/>

<end role= "Products" entityset= "Products"/>

</AssociationSet>

<associationset name= "FK_Orders_Customers" association= "Northwindmodel.fk_orders_customers" >

<end role= "Customers" entityset= "Customers"/>

<end role= "Orders" entityset= "Orders"/>

</AssociationSet>

...

</AssociationSet>

</EntityContainer>

Mapping to storage

SSDL files define the structure of relational data in a database. In this example, it also uses the EntityType and association XML elements to declare the structure of the tables and foreign keys that exist in the database, respectively. The namespace of the SSDL file is set based on the name of the database used in the EDM, and its EntityContainer element is named after the database schema. EntityContainer contains a series of EntitySet and AssociationSet elements that declare instances of tables and relationships represented by EntityType and AssociationType. For each EntitySet in a SSDL file, there is a table in the database that corresponds to it.

If you generate an EDM from a database and open it immediately without modifying the CSDL and SSDL files, you will find these files to be extremely similar. This is because the model is generated directly from the database, so the conceptual model is mapped directly to the logical store. The MSL file contains a direct mapping from CSDL to SSDL. All queries written against the EDM are converted to the generated SQL command. The Entity Framework also supports using stored procedures instead of generated SQL queries.

The entitycontainermapping element is used to map the model (CSDL) to Storage (SSDL). The StorageEntityContainer property represents the name of the EntityContainer in the store, and the CdmEntityContainer property represents the EntityContainer corresponding to it in the model. Mapping the model's EntitySet to the stored EntitySet requires the entitysetmapping element. The TypeName property defines the name of the EntitySet in the model, and the StoreEntitySet property defines the name of the EntitySet corresponding to it in the store. The ScalarProperty element allows you to map each property in the model to a store.

<entitysetmapping name= "Products" >

<entitytypemapping typename= "Northwindmodel.products" >

<mappingfragment storeentityset= "Products" >

<scalarproperty name= "ProductID" columnname= "ProductID"/>

<scalarproperty name= "ProductName" columnname= "ProductName"/>

<scalarproperty name= "SupplierID" columnname= "SupplierID"/>

<scalarproperty name= "CategoryID" columnname= "CategoryID"/>

<scalarproperty name= "QuantityPerUnit" columnname= "QuantityPerUnit"/>

<scalarproperty name= "UnitPrice" columnname= "UnitPrice"/>

<scalarproperty name= "UnitsInStock" columnname= "UnitsInStock"/>

<scalarproperty name= "UnitsOnOrder" columnname= "UnitsOnOrder"/>

<scalarproperty name= "ReorderLevel" columnname= "ReorderLevel"/>

<scalarproperty name= "discontinued" Columnname= "discontinued"/>

</MappingFragment>

</EntityTypeMapping>

</EntitySetMapping>

Use EntityClient

Access to the conceptual model of the Entity Framework can be achieved by either of the three different mechanisms (see Figure 1). Here, I'll introduce EntityClient, the new. NET data provider.

When EntityClient communicates with the conceptual model using its own text-based language called "Entity SQL", it extracts it from the logical store. All entity SQL queries executed using EntityClient are compiled into a command tree that is sent to the store. The query from the conceptual model's entity SQL to the stored down conversion is handled by the Entity Framework.

Classes in EntityClient are similar to classes in common ADO. For example, you use the EntityCommand object to perform a entityclient query, which requires the EntityConnection object to connect to the EDM. When EntityClient interacts with an entity in the EDM, EntityClient does not return an instance of the entity and returns all the results in the DbDataReader object. EntityClient can return a set of standard rows and columns, or you can return more complex representations of hierarchical data through DbDataReader.

The example uses EntityClient to connect to the conceptual model and retrieve a list of customers from London. EntityConnection can accept the full connection string for the conceptual layer or the name of the connection string in the app. config file. The connection string contains a list of metadata files (CSDL, MSL, and SSDL files) and the stored connection string information that is dedicated to the database.

Using System.Data;

Using System.Data.EntityClient;

Using System.Configuration;

...

String connstr = system.configuration.configurationmanager.connectionstrings["NorthwindEntities"]. ConnectionString;

Csharptestentities EDM = new Csharptestentities ();

String connstr = EDM. connection.connectionstring;

String connstr = "name = NorthwindEntities"; Get a connection string using three methods

using (entityconnection conn = new EntityConnection (CONNSTR))

{

String sqlstr = "Select VALUE c from Northwindentities.customers as C";

Conn. Open ();

EntityCommand ecmd = new EntityCommand (SQLSTR, conn);

Executedbdatareader, ExecuteNonQuery, ExecuteReader, ExecuteScalar, etc.

EntityDataReader EDR = Ecmd. ExecuteReader (commandbehavior.sequentialaccess);

while (EDR. Read ())

{

Console.WriteLine (edr["CompanyName"]);

}

Console.WriteLine (Ecmd. ToTraceString ());

}

Console.read ();

Using Object Services

Another way to interact with the data represented by the EDM is to use Object Services. With Object Services, you can load objects and navigate any relationships defined in the EDM. As shown in 1, the object service uses EntityClient to get the data. The object service adds identity resolution, which is a manual process when using a DataSet. It also provides object persistence and tracking changes to events to allow explicit loading and saving. This will shorten the round trip to the server.

The object service allows you to return directly to the object list (both projected and defined entities can be returned). For example, using Object Services, you can retrieve list<customers> by definition in the EDM. You can examine the Customers object, change the value, and then save the data to the database again.

If you use a projection with the object service, the returned data will be an object that is not updatable. Because the projection returns specific properties of the entity rather than the entire entity, the object service cannot save the update of the projected data to the database again. If you want to update the data, a better choice is to return the entire entity instead of using the projection.

You can use Object Services to execute queries using entity SQL, or you can write queries using LINQ to entities. The following example shows how to use Object Services and entity SQL to query to retrieve the Customers list:

Using System.Data.Objects;

...

using (var EDM = new NorthwindEntities ())

{

String esql = "Select value c from Northwindentities.customers as C order by C.customerid limit 10";

objectquery<customers> query = EDM. Createquery<customers> (ESQL);

objectresult<customers> results = query. Execute (mergeoption.notracking);

foreach (Customers C in results)

Console.WriteLine (C.customerid + ":" + c.companyname);

Console.WriteLine (query. ToTraceString ());

}

In the EDM, EntityContainer is represented by a class that inherits from ObjectContext (in this example, Northwindcontext). The ObjectContext class implements the Objectquery<t> interface so that it can create queries using entity SQL or LINQ.

The CreateQuery method accepts a parameterized entity SQL statement that defines the query that will retrieve the list of Customers entities. The actual SQL statement that acts on the database is executed when the objectquery<customers> is iterated by using a foreach statement.

Use LINQ to Entities

You can write dynamic queries in entity SQL and use them with Object Services to interact with EDM entities. However, the Entity Framework can also be used in conjunction with the use of the LINQ to entities strongly typed EDM classes. For example, in the example just shown, you can modify queries using Object Services and entity SQL to query using LINQ to Entities, as follows:

objectquery<customers> customerslist = EDM. Customers;

Iqueryable<customers> Customersresult = from Customers in customerslist

where customers. City = = "London"

Select Customers;

foreach (Customers C in Customersresult)

Console.WriteLine (C.customerid + ":" + c.companyname);

This code example replaces all text-based syntax for entity SQL with strongly typed LINQ syntax supported by C # 3.0.

Conclusion

With the Entity Framework, developers can focus on data through the object model rather than the logical/relational data model. Once the design of the EDM is completed and mapped to the relational store, you can interact with objects using a variety of techniques, such as EntityClient, Objectservices, and LINQ.

Entity Framework Learning Summary: Overview of the ADO Entity Framework

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.