Database Reference
In-Depth Information
// using our vwLibrary view
using (var context = new EF6RecipesContext())
{
var items = context.vwLibraries;
foreach (var item in items)
{
Console.WriteLine("{0} {1}", item.FirstName, item.LastName);
Console.WriteLine("\t{0} ({1})", item.Title, item.MeterName);
}
}
In the first block of code in Listing 2-2, we create instances of the Poet, Poem, and Meter entity types for the poet
John Milton, his poem “Paradise Lost,” and the meter for the poem, which in this case is Iambic Pentameter. Once we
have created the instances of the entity types, we set the poem's Meter property to the meter instance and the poem's
Poet property to the poet instance. Using the same approach, we build up the other entities relating each poem to its
meter and poet. Once we have everything in place, we call SaveChanges() to generate and execute the appropriate
SQL statements to insert the rows into the underlying database.
The output from the code in Listing 2-2 is as follows:
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 and initializing instances of the poet, poem, and meter for the first of John
Milton's poems. Once we have these in place, we set the poem's Meter navigation property and the poem's Poet
navigation property to the instances of poem and meter. Now that we have the poem instance completed, we add it
using the Add() method. Entity Framework does all of the remaining work of adding the poem to the Poems collection
on the poet instance and adding the poem to the Poems collection on the meter instance. The rest of the setup follows
the same pattern. To shorten the code, we reuse variables and instances where we can.
Once we have all of the objects created and all the navigation properties initialized, we have completed the
object graph. Entity Framework keeps track of the changes we've made to build the object graph. These changes
are tracked in the database context. Our context variable contains an instance of the database context (it's of type
DbContext), and it is what we used to build the object graph. To send these changes to the database, we call the
SaveChanges() method.
 
Search WWH ::




Custom Search