One of the learning summaries of Entity Framework: Overview of ADO. Net object framework

Source: Internet
Author: User

Ado. netEntity Framework Overview

The new version of ADO. NET features the New Entity Framework. It allows developers to focus on data through the Object Model (instead of the logical/Relational Data Model. The Entity Framework helps to abstract the logical data architecture into a conceptual model, and allows you to provideProgramInteraction with the conceptual model.

The Entity Framework abstracts the logical database structure using the conceptualmodels, ings, and storagemodels. The standby option of entityclient is object service. Specifically, the object service in the Entity Framework helps reduce the data access that developers need to write.Code.

 

Entity Framework components

The Entity Framework allows developers to write less data access code, reduce maintenance, abstract the data structure into a more convenient way to carry out business (less standardized), and facilitate data persistence. When used in combination with LINQ to entities, since the Entity Framework generates strongly typed classes from the conceptual model, it also helps reduce the number of errors during compilation.

The Entity Framework generates a conceptual model that developers can write code based on. Use a new data provider named entityclient and a new language Named Entity SQL, similar to a T-SQL, to directly interact with the model. Entityclient has a model similar to the familiar ADO. Net object. The entityconnection and entitycommand objects are used to return dbdatareader. Another way for developers is to use object services through objectquery objects with Entity SQL or LINQ to entities. Object Service allows developers to use the conceptual model to generate classes that provide features such as strongly typed objects and persistence (see figure 1 ).

Figure 1 Entity Framework Overview

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

 

Entity Data Model

The core of an object framework lies in its model. The Entity Framework supports logical storage models that represent relational architectures in databases. Relational databases usually store data in different ways than applications use data. Generally, this forces developers to retrieve data based on the structure of the database containing data. Therefore, developers usually load data into business entities that are more suitable for processing business rules. In this example, the relational database architecture is represented by a logical model, and the business entity represents the conceptual model. The Entity Framework uses the ing layer to build bridges between models. Therefore, the Entity Framework Model has three active layers:

· Concept Layer

· Ing Layer

· Logic layer

These three layers allow you to map data from a relational database to a more object-oriented business model. The Entity Framework provides methods to define these layers using XML files. It also generates a series of classes based on the conceptual model architecture. You can program these classes to directly interact with data. This provides an abstraction level, so developers can program conceptual models rather than relational models. The Entity Framework maps all commands for conceptual model encoding to the logical model (see figure 2 ).

Figure 2 design an object data model (click the image to obtain a large view)

Conceptual ModelIs defined in an XML file using the conceptual Architecture Definition Language (CSDL. CSDL defines the entities and relationships that the business layer of an application knows.Logical Model(Indicating the database architecture) is defined in an XML file using the Storage Architecture Definition Language (SSDL. For example, you may have an entity in the conceptual model, which actually derives its data from multiple tables in the database. The conceptual and logical models can be associated with entities in a one-to-one relationship. However, EDM does not need to link entities in one-to-one mode.Ing Layer(Defined by the msing architecture language (MSL. This ing allows developers to write code for the conceptual model and map these commands to the logical model.

 

Generate Object Data Model

You can use the database as the starting point to generate EDM. You can then manually modify the XML (or use a model tool that may be provided in a future version of Visual Studio ). After you add ADO. Net EDM to a project, the wizard guides you through the EDM creation process.

Step 1,Create solution "entityframeworktest" and console application "efprojecchloroform ".

Step 2,Add the "ADO. Net Object Data Model" and name it "northwindef. edmx ".

Then select "generate from database". If poco development mode is adopted later, you can select "Empty model".

It is created successfully. Northwindef. edmx contains CSDL, SSDL, and MSL. You can use NotePad to view its structure, copy it, change the extension to XML, and open it in vs2010.


AnalysisCSDL

Metadata residing in the CSDL file contains a series of entities and relationships. The entities are represented by the entitytype element, and the relationships are represented by the association element. An object contains a series of scalar attributes used to define an object. The key attribute indicates the attribute that is critical to the object. Compound keywords are expressed by separating each attribute name with spaces. An object can also contain a special type of property named "navigationproperty. This defines how to navigate from one object to another 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 = "40" Unicode = "true" fixedlength = "false"/>

<Property name = "contactname" type = "string" maxlength = "30" Unicode = "true" fixedlength = "false"/>

...

<Navigationproperty name = "orders" relationship = "northwindmodel. fk_orders_customers" fromrole = "customers" torole = "orders"/>

<Navigationproperty name = "customerdemographics" relationship = "northwindmodel. customercustomerdemo" fromrole = "MERs" torole = "customerdemographics"/>

</Entitytype>

The following CSDL segment 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 indicates the associated participant. In this example, a mers MERs object is associated with an orders object. According to the definition of the diversity, a mers MERs 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 the entityset and associationset elements define the scopes of entities and relationships. All "sets" that should be logically combined are included in the entitycontainer element.

The following CSDL snippet shows entitycontainer and its parts:

<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>


Map to storage

The SSDL file defines the structure of relational data in the database. In this example, the entitytype and association XML elements are used to declare the table and foreign key structures in the database respectively. The namespace of the SSDL file is set based on the name of the database used in EDM, and its entitycontainer element is named after the database architecture. Entitycontainer contains a series of entityset and associationset elements that declare instances of tables and relationships represented by entitytype and associationtype. Each entityset In the SSDL file has a corresponding table in the database.

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

The entitycontainermapping element is used to map a model (CSDL) to storage (SSDL ). The storageentitycontainer attribute indicates the name of the entitycontainer in the storage, while the cdmentitycontainer attribute indicates the entitycontainer in the model. To map the entityset of the model to the stored entityset, The entitysetmapping element is required. The typename attribute defines the name of the entityset in the model, while the storeentityset attribute defines the name of the entityset in the storage. Each attribute in the model can be mapped to storage through the scalarproperty element.

<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>


UseEntityclient

You can use either of the three mechanisms to access the conceptual model of an object framework (see figure 1 ). Here, I will introduce entityclient, a new. NET data provider.

When entityclient uses its own text-based language named "Entity SQL" to communicate with the conceptual model, it will be extracted from the logical storage. All Entity SQL queries executed using entityclient are compiled into the command tree sent to storage. The Entity Framework processes the downward conversion from the Entity SQL of the conceptual model to the storage.

Classes in entityclient are similar to those in common ADO. net providers. For example, if you use the entitycommand object to execute the entityclient query, you need to connect the entityconnection object to EDM. When the entityclient interacts with the entity in EDM, The entityclient returns all results in the dbdatareader object instead of returning the entity instance. Entityclient can return a set of standard rows and columns, or return more complex hierarchical data representation through dbdatareader.

The example uses entityclient to connect to the conceptual model and retrieve the list of customers from London. Entityconnection can accept the full connection string of the concept 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 database-specific connection string information.

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"; // you can use three methods to obtain the connection string.

Using (entityconnection conn = new entityconnection (connstr ))

{

String sqlstr = "select value c from northwindentities. MERs 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 ();


Use object service

Another way to interact with data represented by EDM is to use object service. Through object service, you can load any relationships between objects and navigation defined in EDM. 1. Object Service uses entityclient to obtain data. The object service adds identity resolution. When dataset is used, this identity resolution is a manual process. It also provides tracking changes to object persistence and events to allow explicit loading and saving. This will shorten the round-trip with the server.

Object Service allows you to directly return to the Object List (you can return both projection and defined objects ). For example, you can use object service to retrieve the list <customers> as defined in EDM. You can check the MERs object, change the value, and save the data to the database again.

If projection is used with object service, the returned data is non-updatable. Because the projection returns the specific attributes of the object rather than the whole object, the object service cannot save the update of the projection data to the database again. If you want to update data, it is better to return the entire object instead of using projection.

You can use object service to execute queries using Entity SQL, or write queries using LINQ to entities. The following example shows how to use object service and Entity SQL to query the MERs list:

Using system. Data. objects;

...

Using (var edm = new northwindentities ())

{

String esql = "select value c from northwindentities. MERs 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 EDM, entitycontainer is represented by a Class inherited from objectcontext (northwindcontext in this example. Objectcontext class implements the objectquery <t> interface so that it can use Entity SQL or LINQ to create a query.

The createquery method accepts parameterized Entity SQL statements that define queries that retrieve the customers Object List. When you use the foreach statement to iterate the objectquery <customers>, the actual SQL statement acting on the database is executed.


UseLINQ 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 combination with the highly typed EDM class using the LINQ to entities. For example, in the example shown just now, you can modify the query using object service and Entity SQL to use LINQ to entities for query, as shown below:

Objectquery <customers> customerslist = EDM. customers;

Iqueryable <customers> customersresult = from customers in customerslist

Where customers. City = "London"

Select MERs MERS;

Foreach (customers C in customersresult)

Console. writeline (C. customerid + ":" + C. companyName );

In this code example, all text-based Syntax of Entity SQL is replaced by the strongly typed LINQ syntax supported by C #3.0.


Conclusion

With the Entity Framework, developers can focus on data through the Object Model (instead of the logical/Relational Data Model. Once EDM is designed and mapped to relational storage, you can use entityclient, objectservices, and LINQ to interact with objects.

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.