Entity Framework 6 Recipes Translation Series (4)-----Chapter II the foundation of Entity Data modeling from existing database creation model

Source: Internet
Author: User
Tags joins scalar

I do not know that there is not much interest in EF, or I translate a problem (if so, I implore you to correct), through the previous few feedback, reading this series of people are not many. Do not this matter to finally become to eat not to please the matter on the trouble, nonsense on to here, straight to the subject.

2-2 creating a model from an existing database

  Problem

  There is an existing database that has tables, perhaps views, and foreign keys. You want to create a model from it.

  Solution Solutions

Let's imagine that you have a database describing poets (poet) and their poems (Poem), and their relationships. As shown in 2-7.

  

Figure 2-7 A simple database of poets and their poems

  As can be seen, a poet may be the author of one or more poems, each poem can be classified according to its rhythm, rhyme is the basic pattern of verse. The view that joins tables together in the database is not displayed, which makes it easier to enumerate poets, poems, and rhymes.

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

1. Right click on your project, select Add (add)? New Item.

2. Select the ADO data model under the data template under the Visual C # Entry (ADO).

3. Select generate from database to create a model from an existing one, click Next.

4, you can choose an existing database connection, you can also choose to create a new database connection, if you choose New, you will choose the database server, authentication method (Windwos or SQL server) and a database. Once you've chosen it, you can click Test Connection (test connection) to see if the connection is available. After the test is finished, click Next.

The dialog box that pops up shows all the tables, views, and stored procedures for the database. Select the items that you want to include in the model. We select all the tables (Meter,poem,poet), the View (vwlibrary), and then tick on the "plural" form that determines the name of the generated object, including the foreign key column in the Model check box. We will discuss this further. Figure 2-8 shows the choices we make.

  Figure 2-8 Selecting a table, a view containing a model, checking the single and plural form that determines the name of the generated object, including the foreign key column in the Model check box

When you click Finish, the wizard generates a model with three tables and a view. The wizard reads the FOREIGN KEY constraint from the database and deduces a one-to-many relationship between poet and poem (s), as well as a a-to-many relationship between meter and poem (s).

Figure 2-9 Conceptual model

Figure 2-9 shows a model that contains table poet,poem and meter, view vwlibrary.

Now you have a model that you can use in your code. Note that the Vwlibrary entity is vwlibrary based on the view in the data. In the vast majority of libraries, views are read-only, and insertions, deletions, and updates are not supported. The same is true in the Entity Framework, where the Entity Framework treats views as read-only. You can map stored procedures to resolve create, update, and delete actions for view-based entities. We will demonstrate this in the sixth chapter.

  Principle

  Let's take a look at the model that the Import Wizard created for us. Note that scalar attributes and navigation properties are already included in the entity. Scalar properties are mapped to columns in a database table, but the navigation properties come to the inter-table relationship in the database.

In a database diagram, a poem has a meter and a poet (author). This conforms to the navigation properties in meter and poet. If I have an instance of a poem entity, the navigation property poet will reference an instance of a poet entity, and the navigation property meter will reference an instance of the meter entity.

A poet may be the author of more than one poem, and its navigation property poems contains a collection of instances of a poem entity. This collection may be empty, which means that the poet has not yet created any poem. For meter entities, the navigation property poems is also a collection. The Navigation property contains a collection of poem entity instances that belong to the specified meter. SQL Server does not support creating relationships on views, which are reflected in the model as a vwlibrary entity without a directed property.

The Import wizard has a very clever representation of the name of the navigation property that contains the collection in the plural form. When you right-click on the entity to view his properties, you will see that the entity set name for each entity is also in the plural form. For example, the entity set name for the poem entity is poems. This automatically adds complex numbers to the benefit, tick the check box on the single plural form that determines the name of the generated object.

Tick the Include Foreign key column check box option in the model so that the foreign key is also included in the model. Although it seems that there is no need to have a foreign key attribute while owning a navigation property. For the citation, we will demonstrate the benefits of having a direct access to the foreign key attribute in the next tip.

Listing 2-2 shows how to create an instance of Poet,poem and meter entities in the model and save them to the data. It also demonstrates how to get poets and poems from the database by querying the model.

code Listing 2-2. Inserting and querying in a model

1  using(varContext =NewEf6recipescontext ()) {2                 varPoet =NewPoet {FirstName ="John", LastName ="Milton" };3                 varPoem =NewPoem {Title ="Paradise Lost" };4                 varmeter =NewMeter {metername ="iambic pentameter" };5Poem. Meter =meter;6Poem. Poet =poet;7 context. Poems.add (poem);8Poem =NewPoem {Title ="Paradise regained" };9Poem. Meter =meter;TenPoem. Poet =poet; One context. Poems.add (poem); APoet =NewPoet {FirstName ="Lewis", LastName ="Carroll" }; -Poem =NewPoem {Title ="The hunting of the Shark" }; -meter =NewMeter {metername ="anapestic tetrameter" }; thePoem. Meter =meter; -Poem. Poet =poet; - context. Poems.add (poem); -Poet =NewPoet {FirstName =" Lord", LastName ="Byron" }; +Poem =NewPoem {Title ="Don Juan" }; -Poem. Meter =meter; +Poem. Poet =poet; A context. Poems.add (poem); at context. SaveChanges (); -             } -             using(varContext =NewEf6recipescontext ()) { -                 varPoets =context. Poets; -                 foreach(varPoetinchpoets) { -Console.WriteLine ("{0} {1}", poet. FirstName, poet. LastName); in                     foreach(varPoeminchpoet. Poems) { -Console.WriteLine ("\t{0} ({1})", poem. Title, poem. Meter.metername); to                     } +                 } -             } the  *             //working with views vwlibrary $             using(varContext =NewEf6recipescontext ()) {Panax Notoginseng                 varItems =context.vwlibraries; -                 foreach(varIteminchitems) { theConsole.WriteLine ("{0} {1}", item. FirstName, item. LastName); +Console.WriteLine ("\t{0} ({1})", item. Title, item. Metername); A                 } the}

in code listing 2-2, the first block of code, we created an instance of the Poet,poem and meter entity types, the poet John Milton, his poem "Paradise Lost" and the Rhythm of the poem, which belonged to the five-step Caron-iambic Pentameter (a rhyme of poetry). Once we create an instance of the poem entity type Peom and set the meter property of the poem to point to the meter instance, the poet attribute points to the poet instance. Using the same method, we create other entities and relationships. Once created, we can call the SaveChanges () method to generate and execute the appropriate SQL statement to insert data into the underlying database.

The output of code listing 2-2 is sent:

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 start by creating instance poet,poem and the prosodic meter of John Milton's first poem. Once we have created it, we can set the poem navigation property meter to meter instance, and the poet navigation property is the poet instance. All the settings for the instance poem are complete, and the Add () method is called to be added to the context. The next work will be done by the Entity Framework, including adding poem to the poet instance's navigation properties poems collection, adding poem to meter instances of the navigation properties poems collection. Use the same steps to complete the remaining tasks. To reduce the code, we reused the variables and instances.

Once all instances have been created and the navigation properties are initialized, we have completed the creation of an object graph. The Entity Framework keeps all modifications to the creation of the object graph, which is implemented in the context of the database. The variable context contains an instance of a database context (its type is DbContext), which is the object we use to track modifications made to the object graph, and calls its SaveChanges () method to send all modifications to the database.

Then you can query the model to verify the data that we saved in the database. We used a new context object and queried using LINQ to Entities. We could have reused the previous context object, but we knew that it had an object graph in memory, and that the next query would not be retrieved directly from memory through the database (this would not be possible for verification purposes).

Using LINQ to Entities, we queried all the poets (poets) and then printed out the names of each poet and the details of each poet's poem. The code is very simple, but it is implemented using two nested loops.

The last block of code uses the Vwlibrary entity, which is based on the Vwlibrary view. The Vwlibrary view joins tables together to flatten them to provide a clearer perspective. When we query each poet's information through the Vwlibraties entity set, only one loop is needed. The output is slightly different because we repeat the poet's name in each poem.

The last note in this example is that we did not insert poests,poems and meters through the view vwlibrary. Because in the vast majority of databases, views are read-only. In the Entity Framework, we also cannot be able to insert (or update, delete) entities from a view entity. Of course, we will show you how to overcome this difficulty in the later part of this book!

This is the right place to go. Get the food to eat. If you feel good, please click on the lower right corner of the recommendation, one is to give me motivation, and secondly, to share to more people. Thank you.

 

Entity Framework 6 Recipes Translation Series (4)-----Chapter II the foundation of Entity Data modeling from existing database creation model

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.