Database Reference
In-Depth Information
// Nanoxol just got approved!
exDrug1.PromoteToMedicine(DateTime.Now, 19.99M, "Treatall");
context.Entry(exDrug1).State = EntityState.Detached // better not use this instance any longer
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("Experimental Drugs");
foreach (var d in context.Drugs.OfType<Experimental>())
{
Console.WriteLine("\t{0} ({1})", d.Name, d.PrincipalResearcher);
}
Console.WriteLine("Medicines");
foreach (var d in context.Drugs.OfType<Medicine>())
{
Console.WriteLine("\t{0} Retails for {1}", d.Name,
d.TargetPrice.Value.ToString("C"));
}
}
}
}
Following is the output of the code in Listing 6-19:
Experimental Drugs
Percosol (Dr. Bill Minor)
Medicines
Treatall Retails for $19.99
We change an Experimental drug to a Medicine using the PromoteToMedicine() method. In the implementation
of this method, we create a new Medicine instance, attach it to a new DbContext, and initialize it with the appropriate
new values. Once the new instance is attached and initialized, we use the SaveChanges() method on the DbContext
to save the new instance to the database. Because the instance has the same key (DrugId) as the Experimental drug,
Entity Framework generates an update statement rather than an insert statement.
We implemented the PromoteToMedicine() method inside the POCO class Experimental . This allows us
seamlessly to add the method to the class, and it provides for a much cleaner implementation. That being said, in the
interest of creating persistence-ignorant POCO entities that can be used in multiple DbContexts, it might make more
sense to implement a slightly altered version of this method in a helper class instead.
6-7. Modeling Table per Type Inheritance Using a Nonprimary
Key Column
Problem
You have one or more tables in an existing schema that have a one-to-one relationship to a common table using keys
that are not primary keys in the tables. You want to model this using Table per Type inheritance.
 
Search WWH ::




Custom Search