Database Reference
In-Depth Information
public class Medicine : Drug
{
public decimal? TargetPrice { get; set; }
public DateTime AcceptedDate { get; set; }
}
3.
Add an auto-property of type DbSet<Drug> to your DbContext subclass.
4.
Override the OnModelCreating method of DbContext to configure the TPH mapping for
Medicine and Experimental types, as shown in Listing 6-18.
Listing 6-18. Overriding OnModelCreating to Configure TPH Mapping
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Experimental>()
.Map(m => m.Requires("AcceptedDate").HasValue((DateTime?)null));
modelBuilder.Entity<Medicine>()
.Map(m => m.Requires(d => d.AcceptedDate).HasValue());
}
How It Works
In this example, we made use of the null and is not null conditions to map a Drug without an AcceptedDate to an
Experimental drug and a Drug with an AcceptedDate to a Medicine. As in many inheritance examples, we marked the
base entity, Drug, as abstract because in our model we would never have an uncategorized drug.
It is interesting to note that, in the Medicine entity, we mapped the AcceptedDate discriminator column to a
scalar property. In most scenarios, mapping the discriminator column to scalar property is prohibited. However, in
this example, our use of the null and is not null conditions, as well as marking the AcceptedDate as not nullable,
sufficiently constrains the values for property to allow the mapping.
In Listing 6-19, we insert a couple of Experimental drugs and query the results. We take the opportunity provided
by the exposed AcceptedDate property to demonstrate one way to change an object from one derived type to another.
In our case, we create a couple of Experimental drugs and then promote one of them to a Medicine.
Listing 6-19. Inserting and Retrieving Instances of Our Derived Types
class Program
{
...
static void RunExample()
{
using (var context = new EF6RecipesContext())
{
var exDrug1 = new Experimental { Name = "Nanoxol",
PrincipalResearcher = "Dr. Susan James" };
var exDrug2 = new Experimental { Name = "Percosol",
PrincipalResearcher = "Dr. Bill Minor" };
context.Drugs.Add(exDrug1);
context.Drugs.Add(exDrug2);
context.SaveChanges();
 
Search WWH ::




Custom Search