Database Reference
In-Depth Information
.HasMany(p => p.Fans)
.WithOptional(p => p.Hero)
.Map(m => m.MapKey("HeroId"));
modelBuilder.Entity<Person>()
.Map<Firefighter>(m => m.Requires("Role").HasValue("f"))
.Map<Teacher>(m => m.Requires("Role").HasValue("t"))
.Map<Retired>(m => m.Requires("Role").HasValue("r"));
}
How It Works
The code in Listing 6-11 demonstrates inserting and retrieving Person entities from our model. We create a single
instance of each of the derived types and wire in a few hero relationships. We have a teacher who is the hero of a
firefighter and a retired person who is the hero of the teacher. When we set the firefighter as the hero of the retired
person, we introduce just enough of a cycle so that Entity Framework generates a runtime error (a DbUpdateException)
because it cannot determine the appropriate order for inserting the rows into the table. In the code, we get around
this problem by calling the SaveChanges() method before wiring in any of the hero relationships. Once the rows are
committed to the database, and the store-generated keys are brought back into the object graph, we are free to update
the graph with the relationships. Of course, these changes must be saved with a final call to SaveChanges() .
Listing 6-11. Inserting into and Retrieving from Our Model
using (var context = new EF6RecipesContext())
{
var teacher = new Teacher { Name = "Susan Smith",
School = "Custer Baker Middle School" };
var firefighter = new Firefighter { Name = "Joel Clark",
FireStation = "Midtown" };
var retired = new Retired { Name = "Joan Collins",
FullTimeHobby = "Scapbooking" };
context.People.Add(teacher);
context.People.Add(firefighter);
context.People.Add(retired);
context.SaveChanges();
firefighter.Hero = teacher;
teacher.Hero = retired;
retired.Hero = firefighter;
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
foreach(var person in context.People)
{
if (person.Hero != null)
Console.WriteLine("\n{0}, Hero is: {1}", person.Name,
person.Hero.Name);
else
Console.WriteLine("{0}", person.Name);
 
Search WWH ::




Custom Search