EF Overview of the Entity Framework 5.0 series-Three ways to program __ programming

Source: Internet
Author: User

http://www.cnblogs.com/kenshincui/p/3280742.html#autoid-0-0-0



Overview

When developing data-oriented software, we often make the effort to solve business problem entities, relationships, and logical building models, and the creation of ORM provides us with an elegant solution. The Ado.net Entity Framework is a ado.net-driven ORM framework in. NET development that enables Entity framework developers to work at higher levels of abstraction when working with data without having to consider the underlying data tables and columns of the data. and the ability to write less code to create and maintain applications with relatively traditional development.

We know that object-oriented programming and data Storage System Exchange presents a difficult problem: class structure is usually similar to the relational data table organization structure but also different. For example, a foreign key may be used in the data to represent a relationship between an entity and another entity, but for a class we notice that a property is defined in the class to describe the relationship. For this problem the current ORM framework generally chooses to compensate for this deficiency by mapping object-oriented classes and attributes to relational tables and columns. However, the Entity Framework does not take this approach but maps the tables, columns, and foreign KEY constraints in the logical model to entities and relationships in the conceptual model, and the Entity Data Model tools generate scalable data classes based on the conceptual model. These classes derive from the base class, and the base class provides services to materialize entities as objects and to track and save them. This makes it easy for developers to extend data classes and to handle entities and relationships just as they do with associated objects. three ways of programming

Before Entity Framework4.1, EF supported "Database first" and "Model first" programming, starting with the EF support for "Code first" programming from EF4.1, and today we'll take a quick look at EF three programming methods.

Before you begin to describe these three EF operations, first establish a database connection in Visual Studio 2013, where we take the "AdventureWorks" database as an example:

Database A

"Database First" is what we call "db precedence" if your application already has a database, you can use the EF design tool to generate data classes from the database, and you can use the Visual Studio Model Designer to modify the corresponding relationships between the models.

First create a console application, then right-click to add New item, select "Ado.net Entity Data Model", name enter Adventureworkscontext:

Then choose to build from the database:

Next, select the database Connection "SQL2008." Adventureworks.dbo ":

Click Next, and then select Person and Personphone tables:

After you create the model, you will find that Visual Studio automatically generates the "Perrson", "Personphone" two entity classes, and a "Adventureworkscontext" database Context action class for you:

The following is a simple look at how to use EF for data querying, and we can see how elegant EF is for data manipulation in the following code:

Using System;
Using System.Collections.Generic;
Using System.Linq;

Using System.Text;  Namespace Databasefirst {class Program {static void Main (string[] args) {using (var db = new AdventureWorksEntities ()) {iqueryable<person> persons = from people in db. People where people.
                LastName = = "Sánchez" Select people;
                    foreach (person p in persons) {Console.WriteLine ("The name is: {0}", p.firstname); if (P.firstname = = "Angela") {p.additionalcontactinfo = "
                    Other Info "; } var persons2 = from people in db. People where people. LastName = = "Sánchez" && people.
   FirstName = = "Angela" Select people;             if (persons2. Count () > 0) {Console.WriteLine ("Additional contacts information is: {0}", Persons2 . A ().
                AdditionalContactInfo);
 Although the above can be traced out addtionalcontactinfo, but the actual province has not been saved to the database, the specific save method is no longer described in detail}}

The results of the implementation are shown below:

Note: If your database table structure changes, just right-click in the blank space of the Model Design view, select "Update model from database" and follow the wizard.
Model A

Model First we call it "model priority", where the models refer to "Ado.net Entity Framework Data model", at which point your application does not design the relevant database, in visual In Studio we build databases and data classes by designing the data model for.

First create a console application, right-click Add New Item, select "Ado.net Entity Data Model", name input Adventureworkscontext:

Then select the empty model:

In model Design view, add a new entity:

Enter the properties for the entity:

Add, two scalar properties: "Customer" and "OrderDate"; Add the second entity "OrderDetail" in the same way and add the "Product" and "UnitPrice" Properties:

Next we add the relationship between the two, "Order" and "OrderDetail" is a one-to-many relationship, "order" can be accessed through the "OrderDetails" attribute to the "OrderDetail" entity, "OrderDetail" can pass " The Order property accesses the "??" entity and adds a foreign key constraint to "OrderDetail":

After you have added a relationship:

The model in the Model A has been created so far, and the following needs to be built into the database, and in the Design view space, select "Build from model to database ...":

To select a database connection, click Next and you will see the resulting SQL statement:

Click to complete, no surprises will open the generated script, of course, you may also have the following error, please download the latest SQL Server Data Tool (my local VS2012, database sqlserver2008r2 appears the following prompts, download the update can, Recommended direct download of mirrored files):

The database context and entity classes are generated, and the script that builds the table is opened:

Open Database script:

Then right-click to select Execute.

Then encode the query:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Modelfirst
{
    class program
    {
        static void Main (string[] args)
        {
            using (var dbcontext =new Adventureworkscontextcontainer ())
            {
                var o = New Order ();
                O.orderdate = DateTime.Now;
                CTx. Orders.add (o);
                CTx. SaveChanges ();

                var orders = from od in dbcontext.orders
                            select OD;

                foreach (Order order2 in orders)
                {
                    Console.WriteLine ("Orderid:{0},orderdate:{1}", Order2. Id,order2. OrderDate);
                }

                Console.read ();}}}

Query results:

Note: If our model changes, just modify the model in the model Design view, and then save the entity class accordingly, then select "Build from model to database" to rerun the generated script.
Code A

The code first mode, which we call "coding priority" mode, is a new join function from EF4.1. When using the code-S model for EF development, developers only need to write the corresponding data classes (in fact, the implementation of the domain model), and then automatically generate the database. The advantage of this design is that we can do all the data operations on the conceptual model without having to store relationships with the data, making it more natural for us to adopt object-oriented approaches to data-oriented application development.

In some ways, the distinction between "code first" and "model first" is not too obvious, except that it does not rely on the Entity Data Model Designer, but instead designs the entity model directly by encoding (data Class) (which is why "code first" is called "code Only "reason). However, there are differences in the processing of the EF, for example, we no longer need the EDM file with code A, and all mappings are mapped and configured through the data annotation and the fluent APIs. It is also important to note that "Code number one" does not necessarily mean that the model must be defined through a data class, but it can actually generate data classes from an existing database.

So let's take a look at how the traditional code first is used.

First create a console application, then add two classes "order" and "OrderDetail", we can see that these two classes are just simple C # objects (Poco,plain old C # object) These two classes have nothing to do with EF. It should be noted that these two classes have two navigation properties "Order.orderdetails" and "Orderdetail.order":

Using System;
Using System.Collections.Generic;

Namespace Codefirst
{public
    class order
    {public
        int Id {get; set;}
        public string Customer {get; set;}
        Public System.DateTime OrderDate {get; set;}
    
        Public virtual list<orderdetail> OrderDetails {get; set;}}}
Using System;
Using System.Collections.Generic;

Namespace Codefirst
{public
    partial class OrderDetail
    {public
        int Id {get; set;}
        public string Product {get; set;}
        public string UnitPrice {get; set;}
        public int OrderId {get; set;}
    
        Public virtual order: {get; set;}}}

With these two classes, let's define a database context, and with it we can do a System.Data.Entity.DbContext of the data, which must be inherited from the class to give it the ability to manipulate data. So next we need to install the EntityFramework package for this application because so far we have not introduced anything related to the EF framework, we need to introduce an EF-related assembly. But we have a better choice, and that's nuget. On-line installation via NuGet: In the project, select "Manage NuGet Packages ..."; select online; then select "EntityFramework"; then click Install. Don't know NuGet's friends come here and have a look. Use NuGet to manage the project library. Database context Action class:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using System.Data.Entity;


Namespace Codefirst
{public
    class Ordercontext:dbcontext
    {public

        dbset<order> Orders
        { Get
            ;
            Set;
        }

        Public dbset<orderdetail> OrderDetails
        {get
            ;
            Set;}}}

We then test that in this class we first create an order instance and then encode the query:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Codefirst
{
    class program
    {
        static void Main (string[] args)
        {
            using (var ctx = new OrderContext ())
            {

                var o = New Order ();
                O.orderdate = DateTime.Now;
                CTx. Orders.add (o);
                CTx. SaveChanges ();

                var query = from order in CTX. Orders
                            Select order;
                foreach (var q in query)
                {
                    Console.WriteLine ("Orderid:{0},orderdate:{1}", Q.id, q.orderdate);
                }

                Console.read ();}}}

Query results as shown in figure:

If it is the first time you use the EF Code One, you will have a question, we do not have any database configuration, add a data through the query is actually saved, then our data in the end. In fact, if the user does not make the database configuration EF uses the ". \SQLExpress" database instance by default, if you do not install ". \SQLExpress", the default is to use LocalDB, for specific details on LOCALDB, see: SQL Server 2012 Express LocalDB, for example, where I am stored in: "C:\Users\Kenshin", you can see the creation of a database named "Codefirst.ordercontext":

But most of the time we want to control the database, for example, I want him to save it on my machine's ". \sql2008" instance, at which point we need to configure a database connection string in the configuration file app.config and then specify the connection name in our database context.

Configuration file:

<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
  <configSections>
    <!--for More information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/? linkid=237468-->
    <section name= "EntityFramework" type=

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.