Entity Framework 6 Recipes translation series (4), entityframework

Source: Internet
Author: User

Entity Framework 6 Recipes translation series (4), entityframework

I don't know if I'm not very interested in EF, or if I have some translation problems (if so, please correct me). Through the feedback from the previous articles, there are not many people reading this series. If you don't want to do this, it will eventually become a thankless task. If you don't want to do anything nonsense, go straight to the topic.

2-2 create a model from an existing database

  Problem

There is an existing database with tables, views, and foreign keys. You want to use it to create a model.

  Solution

Let's imagine that you have a database describing Poet and their poems and their relationships. From 2 to 7.

  

Figure 2-7 a simple database of poets and Their Poems

It can be seen that a poet may be the author of one or more poems. Each poem can be classified according to its rhythm. rhythm is the basic mode of verse. The database does not show views that connect tables together. It makes it easier for us to enumerate poets, poems, and rhythms.

Follow these steps to import tables, views, and relationships to the model:

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

2. Select ADO. NET Entity Data Model (ADO. NET Entity Data Model) under the Data Template under Visual C ).

3. Select Generate from database to create a model from an existing database and click Next ).

4. You can select an existing database connection or create a new database connection. If you choose to create a new database, you will select the database Server and authentication method (Windwos or SQL Server) and a database. Once selected, you can click Test Connection to Test whether the Connection is available. After testing, click Next ).

The pop-up dialog box displays all tables, views, and stored procedures of the database. Select the items you want to include in the model. Select All Tables (Meter, Poem, Poet), view (vwLibrary), and then select the single and multiple forms of the generated object name and the check box that contains foreign key columns in the model. We will discuss this further. Figure 2-8 shows our selection.

Figure 2-8 select a table and view to be included in the model, and select the check box for determining the complex form of the generated Object Name and including the foreign key column in the model.

Click Finish to generate a model that contains three tables and one view. The wizard reads foreign key constraints from the database, and exports the one-to-many relationship between Poet and Poem (s), and one-to-multiple relationship between Meter and Poem (s.

Figure 2-9 Conceptual Model

Figure 2-9 shows a model that includes the table Poet, Poem, Meter, and view vwLibrary.

Now you have a model that can be used in the code. Note that the vwLibrary object is based on the view vwLibrary in the data. In most databases, views are read-only, and insertion, deletion, and update are not supported. This is also true in the object framework. The object framework regards the view as read-only. You can use the ing stored procedure to create, update, and delete view-based entities. We will demonstrate this in chapter 6.

  Principle

  Let's take a look at the model created by the import wizard for us. Note that the object already contains scalar attributes and navigation attributes. The scalar attribute is mapped to the columns in the database table, but the navigation attribute is mapped to the relationship between tables in the database.

In the database relationship diagram, a poem has a meter and a poet (author ). This complies with the navigation attributes in Meter and Poet. If I have an instance of a Poem object, the navigation attribute Poet references an instance of a Poet object, and the navigation attribute Meter references an instance of a Meter object.

A Poet may be the author of multiple Poems. Its Navigation attribute Poems contains an instance set of Poem entities. This collection may be empty, which means that the poet has not created any poems. For Meter objects, the navigation attribute Poems is also a set. This navigation property contains a set of Poem entity instances of the specified Meter. SQL Server does not support creating relationships in views, which is reflected in the model as a vwLibrary entity with no oriented attributes.

The import wizard is very smart in the form of a single and multiple names containing the navigation attributes of the set. When you right-click an object to view its Properties, you will see that the names of each object set are also in the plural form. For example, the entity set name of the Poem object is called Poems. This type of Automatic Adding of the plural benefit is to select the check box for determining the singular and plural form of the generated object name.

Select the check box that contains the foreign key column in the model to include the foreign key in the model. Although it seems that there is no need to have foreign key attributes while having navigation attributes. In the following example, we will demonstrate the benefits of having a foreign key attribute that can be accessed directly.

Code List 2-2 demonstrates how to create Poet, Poem, and Meter entity instances in the model and save them to the data. It also demonstrates how to obtain poets and poems from the database through the query model.

Code List 2-2.Insert and query in Model

 

1 using (var context = new EF6RecipesContext () {2 var poet = new Poet {FirstName = "John", LastName = "Milton "}; 3 var poem = new Poem {Title = "Paradise Lost"}; 4 var meter = new Meter {MeterName = "Iambic Pentameter"}; 5 poem. meter = meter; 6 poem. poet = poet; 7 context. poems. add (poem); 8 poem = new Poem {Title = "Paradise Regained"}; 9 poem. meter = meter; 10 poem. poet = poet; 11 context. poems. add (poem); 12 poet = new Poet {FirstName = "Lewis", LastName = "Carroll "}; 13 poem = new Poem {Title = "The Hunting of the Shark"}; 14 meter = new Meter {MeterName = "Anapestic Tetrameter"}; 15 poem. meter = meter; 16 poem. poet = poet; 17 context. poems. add (poem); 18 poet = new Poet {FirstName = "Lord", LastName = "Byron"}; 19 poem = new Poem {Title = "Don Juan "}; 20 poem. meter = meter; 21 poem. poet = poet; 22 context. poems. add (poem); 23 context. saveChanges (); 24} 25 using (var context = new EF6RecipesContext () {26 var poets = context. poets; 27 foreach (var poet in poets) {28 Console. writeLine ("{0} {1}", poet. firstName, poet. lastName); 29 foreach (var poem in poet. poems) {30 Console. writeLine ("\ t {0} ({1})", poem. title, poem. meter. meterName); 31} 32} 33} 34 35 // use view vwLibrary36 using (var context = new EF6RecipesContext () {37 var items = context. vwLibraries; 38 foreach (var item in items) {39 Console. writeLine ("{0} {1}", item. firstName, item. lastName); 40 Console. writeLine ("\ t {0} ({1})", item. title, item. meterName); 41} 42}

In the first code block in code list 2-2, we created examples of Poet, Poem, and Meter entity types, the Poet John Milton, his Poem "Paradise Lost", and the rhythm of the Poem, the poem belongs to the five-step yundun-Iambic Pentameter (a rhythm of the poem ). Once we create a Poem entity-type instance peom, and set the Meter attribute of poem to point to the meter instance, the Poet attribute to point to the poet instance. Using the same method, we create other entities and relationships. Once the creation is complete, we can call the SaveChanges () method to generate and execute appropriate SQL statements to insert data in the underlying database.

Output of code list 2-2:

Lord Byron
Don Juan (Anapestic Tetrameter)
Lewis Carroll
The Hunting of the Shark (Anapestic Tetrameter)
John Milton
Paradise Regained (Iambic Pentameter)
Paradise Lost (Iambic Pentameter)
Lewis Carroll
The Hunting of the Shark (Anapestic Tetrameter)
Lord Byron
Don Juan (Anapestic Tetrameter)
John Milton
Paradise Regained (Iambic Pentameter)
John Milton
Paradise Lost (Iambic Pentameter)

In the code, we first created the instance poet, poem, and the rhythm meter of John Milton's first poem. Once created, you can set the poem navigation attribute Meter to the meter instance and the Poet navigation attribute to the poet instance. all settings of the Instance poem have been completed. Call the Add () method to Add it to the context. The following work will be done by the Entity Framework, including adding poem to the Poems set of the navigation attribute of the poet instance, and adding poem to the Poems set of the navigation attribute of the meter instance. Use the same steps to complete the remaining tasks. To reduce code, we reuse variables and instances.

Once all instances are created and the navigation attributes are initialized, an object graph is created. The object framework keeps all modifications to the object graph created, which is implemented in the database context. The variable context contains an instance of the database context (its type is DbContext). It is the object we use to track the modifications made to the created object graph and call its SaveChanges () method, all modifications can be sent to the database.

You can query the model to verify the data stored in the database. We use a new context object and LINQ to Entities for query. We can reuse the previous context object, but we know that it already has an object graph in the memory, and the next query will not get it directly from the memory through the database: in this way, the purpose of verification is not achieved ).

Using LINQ to Entities, we can find all the poets and print out the names of each poet and the details of each poem of the poet. The code is very simple, but it is implemented using two nested loops.

The last code block uses the VwLibrary object, which is based on the vwLibrary view. The vwLibrary view concatenates tables to flatten them to provide a clearer view. When we query related information of each poet through the vwLibraties entity set, we only need one loop. The output is slightly different, because we repeat the poet's name in each poem.

In this example, we do not insert poests, poems, and meters through the view vwLibrary. In most databases, views are read-only. In the object framework, we cannot insert (update or delete) objects in a view. Of course, we will show you how to overcome this difficulty in the later part of this book!

This article is here. I have eaten the meal. If you think it is good, click the recommendation in the lower right corner to give me motivation and share it with more people. 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.