Entity Framework 6 Recipes translation Series 3, entityframework

Source: Internet
Author: User
Tags management studio sql server management sql server management studio

Entity Framework 6 Recipes translation Series 3, entityframework
Chapter 2 basis of Object Data Modeling

It is very likely that you start to explore the Entity Framework. You may ask "How do we start ?", If this is the case, this chapter is a good start. If not, you have already modeled and feel good about entity splitting and inheritance, you can skip this chapter.

This chapter describes the basic examples of modeling using the Entity Framework. modeling is the core feature of the Entity Framework and also the feature of distinguishing the Entity Framework from Microsoft's early data access platform. Once the model is created, you can write code for the model instead of for rows and columns in the relational database.

This chapter begins with creating an instance of a simple conceptual model, and then allows the Entity Framework to create the underlying database. The remaining instances will be displayed to you, how to model through existing tables in the database and their relationships.

2-1 create a simple model

  Problem

You have a brand new item. You need to create a model.

  Solution

We imagine that you need to create an application for management, personnel name, and phone number. To keep it as simple as possible, we assume that you only need one entity type: Person.

To create a model, follow these steps:

1. Right-click your project and select New Item ).

2. Select ADO. NET Entity Data Model (ADO. NET Object Data Model) from the template, and click Add ). The template is under the Data item under the Visual C # entry. (2-1 ).

Figure 2-1 adds a new. emdx file, which contains the conceptual model, storage model, and ing layer described in XML.

3. in step 1 of the wizard, select Empty Model (Empty Model) and click Finish. The wizard creates an empty conceptual model on the designer interface.

4. Right-click the calculator interface and select Add Entity (Entity ).

5. in the Entity Name field, type "Person", select the Create a Key Propety (Create object Key) check box, use Id as the object Key, and make sure its type is Int32. click "OK, A new Person entity appears in the designer window (2-2 ).

Figure 2-2 add an object class representing Person in the conceptual model

6. Right-click the top of the Person object and select Add (Add) Scalar Property (Scalar attribute ). A new scalar attribute is added to the Person object.

7. Rename the added scalar attribute to Firstname. Then add the scalar attributes LastName, MiddleName, and PhoneNumber.

8. Right-click the Id attribute and select Properties. In the Properties window, if the StoreGneneratedPattern attribute value is not set to Identity, set it to Identity. This identifier indicates that the value of the Id attribute will be calculated and generated by the storage layer (database. The final database script will identify the Id column as the identity column, and the storage logic model will know that the database will automatically manage the value of this column.

The completed conceptual model is shown in 2-3.

Figure 2-3 model contains an object type that represents Person

You have completed a simple conceptual model. However, there is still some work to do to generate a database from this model:

9. We need to modify some attributes of our model to help us generate databases. Right-click the calculator window and select properties ). Change the Database Schema name to Chapter2 and the Entity Container Name to EF6ReciptesContext. 2-4.

Figure 2-4 modify model attributes

10. Right-click the designer window and select Generate Database Script from Model (Generate Database Script from Model ). Select an existing database connection or create a new connection. Figure 2-5 shows how to create a new local database EF6Recipes connection.

Figure 2-5 create an object framework and create the database connection to be used by the database script from the conceptual model

11. Click OK to complete the connection Property setting, and then click Next (Next) to preview the database script (2-6 ). Once you click Finish, the generated script is added to your project.

Figure 2-6 generate a storage logic model and create a database script in the. edmx File

12. In the SSMS (SQL Server Management Studio) query window, execute the database script generated above to create a database and a People table.

Principle

The Entity Framework designer is a powerful tool for creating conceptual models, storage models, and ing layers. It provides two-way modeling. You can create a model from a blank model design window, or import an existing database to create a conceptual model, storage model, and ing layer. The current version provides a limited two-way modeling function, which allows you to recreate a database from the model and update the model based on database changes.

The conceptual model has many attributes that affect the generation of storage logic models and database scripts. We have changed two attributes. The first one is the container name, which is inherited to the DbContext context object. We name it EF6RecipesContext, which is consistent with the context object used in this book.

The other is that the schema name indicating that the storage logic model and database script are generated is "Chaper2 ".

The code list 2-1 demonstrates that we create and insert an instance of the Person entity type and save all the Person entities to the database.

Code List 2-1.Insert and retrieve data from the Model

 1             using (var context = new EF6RecipesContext()) { 2                 var person = new Person { 3                     FirstName = "Robert", 4                     MiddleName = "Allen", 5                     LastName = "Doe", 6                     PhoneNumber = "867-5309" 7                 }; 8                 context.People.Add(person); 9                 person = new Person {10                     FirstName = "John",11                     MiddleName = "K.",12                     LastName = "Smith",13                     PhoneNumber = "824-3031"14                 };15                 context.People.Add(person);16                 person = new Person {17                     FirstName = "Billy",18                     MiddleName = "Albert",19                     LastName = "Minor",20                     PhoneNumber = "907-2212"21                 };22                 context.People.Add(person);23                 person = new Person {24                     FirstName = "Kathy",25                     MiddleName = "Anne",26                     LastName = "Ryan",27                     PhoneNumber = "722-0038"28                 };29                 context.People.Add(person);30                 context.SaveChanges();31             }32             using (var context = new EF6RecipesContext()) {33                 foreach (var person in context.People) {34                     System.Console.WriteLine("{0} {1} {2}, Phone: {3}",35                         person.FirstName, person.MiddleName,36                         person.LastName, person.PhoneNumber);37                 }38             }

The output of code list 2-1 is:

John K. Smith, Phone: 824-3031
Robert Allen Doe, Phone: 867-5309
Kathy Anne Ryan, Phone: 722-0038.
Billy Albert Minor, Phone: 907-2212

Best practices
When creating a context instance, we use the using () Statement:

Using (var context = new EF6RecipesContext ())
{
...
}

It doesn't matter if you are not familiar with this mode, because it is very simple. Generally, we use the new operator and assign the result to the variable to get an instance of an object. When the variable exceeds its lifecycle, the object is no longer referenced by any other object. The garbage collector will release the memory occupied by the object at a certain point in time. For most objects in our. NET application, this is a huge job because they occupy resources until the Garbage Collector starts to work. The garbage collector is uncertain, because he always finishes his work on his own plan, and the impact on me is limited.

The instance of the DbContext context object occupies system resources such as database connection, which we want to release immediately when not in use. We really don't want the release of database connections to be completed by the garbage collector.

The using () statement has good features. First, when the Code executes the using () {} code block, the Dispose () method in the context is automatically called. Because the DbContext context implements the IDisposable interface, this method will disable all database connections and clear any resources to be released.

Second, as long as the Code leaves the using () {} code block, the method Dispose () will be called. Most importantly, even if a return statement or an exception is thrown in a code block, the resource can be reasonably released.

The best practice here is,When creating a DbContext context object, the using () {} code block is always used.It will further help you create robust code.

This article is here,If there is any improper translation, please correct me. If you think this series is worth sharing with more people, click the recommendation in the lower right corner..Thank you.. This article is translated by VolcanoCloud. For more information, see the source. Thank you!

 

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.