Database Reference
In-Depth Information
The code in Listing 2-1 demonstrates one simple way to create and insert instances of our Person entity type.
The code also demonstrates iterating through all the Person entities in our database.
Listing 2-1. Inserting into and Retrieving from Our Model
using (var context = new EF6RecipesContext())
{
var person = new Person { FirstName = "Robert", MiddleName="Allen",
LastName = "Doe", PhoneNumber = "867-5309" };
context.People.Add(person);
person = new Person { FirstName = "John", MiddleName="K.",
LastName = "Smith", PhoneNumber = "824-3031" };
context.People.Add(person);
person = new Person { FirstName = "Billy", MiddleName="Albert",
LastName = "Minor", PhoneNumber = "907-2212" };
context.People.Add(person);
person = new Person { FirstName = "Kathy", MiddleName="Anne",
LastName = "Ryan", PhoneNumber = "722-0038" };
context.People.Add(person);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
foreach (var person in context.People)
{
System.Console.WriteLine("{0} {1} {2}, Phone: {3}",
person.FirstName, person.MiddleName,
person.LastName, person.PhoneNumber);
}
}
The output of the code in Listing 2-1 should look something like the following:
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 Practice
When we created a new instance of the database context, we did it within a using() statement:
using (var context = new EF6RecipesContext())
{
...
}
 
Search WWH ::




Custom Search