Database Reference
In-Depth Information
entities are also property pluralized. For example, the entity set name for the Poem entity is Poems. This automatic
pluralization happened because we left the Pluralize or singularize generated object names option checked.
The Include Foreign Key Columns in the model option also caused the foreign keys to be included in the model.
Although it may seem a little unnecessary to have both foreign keys and navigation properties, we'll see in many of the
following recipes that having direct access to the foreign keys can be useful.
The code in Listing 2-2 demonstrates how to create instances of Poet, Poem, and Meter entities in our model and
how to save these entities to our database. The code also shows you how to query the model to retrieve the poets and
poems from the database.
Listing 2-2. Inserting into and Querying Our Model
using (var context = new EF6RecipesContext())
{
var poet = new Poet { FirstName = "John", LastName = "Milton" };
var poem = new Poem { Title = "Paradise Lost" };
var meter = new Meter { MeterName = "Iambic Pentameter" };
poem.Meter = meter;
poem.Poet = poet;
context.Poems.Add(poem);
poem = new Poem { Title = "Paradise Regained" };
poem.Meter = meter;
poem.Poet = poet;
context.Poems.Add(poem);
poet = new Poet { FirstName = "Lewis", LastName = "Carroll" };
poem = new Poem { Title = "The Hunting of the Shark" };
meter = new Meter { MeterName = "Anapestic Tetrameter" };
poem.Meter = meter;
poem.Poet = poet;
context.Poems.Add(poem);
poet = new Poet { FirstName = "Lord", LastName = "Byron" };
poem = new Poem { Title = "Don Juan" };
poem.Meter = meter;
poem.Poet = poet;
context.Poems.Add(poem);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
var poets = context.Poets;
foreach (var poet in poets)
{
Console.WriteLine("{0} {1}", poet.FirstName, poet.LastName);
foreach (var poem in poet.Poems)
{
Console.WriteLine("\t{0} ({1})", poem.Title, poem.Meter.MeterName);
}
}
}
 
Search WWH ::




Custom Search