Database Reference
In-Depth Information
Listing 2-19 demonstrates inserting and retrieving from our model.
Listing 2-19. Inserting and Retrieving Entities in TPT Inheritance
using (var context = new EF6RecipesContext())
{
var business = new Business { Name = "Corner Dry Cleaning",
LicenseNumber = "100x1" };
context.Businesses.Add(business);
var retail = new Retail { Name = "Shop and Save", LicenseNumber = "200C",
Address = "101 Main", City = "Anytown",
State = "TX", ZIPCode = "76106" };
context.Businesses.Add(retail);
var web = new eCommerce { Name = " BuyNow.com ", LicenseNumber = "300AB",
URL = " www.buynow.com " };
context.Businesses.Add(web);
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
Console.WriteLine("\n--- All Businesses ---");
foreach (var b in context.Businesses)
{
Console.WriteLine("{0} (#{1})", b.Name, b.LicenseNumber);
}
Console.WriteLine("\n--- Retail Businesses ---");
foreach (var r in context.Businesses.OfType<Retail>())
{
Console.WriteLine("{0} (#{1})", r.Name, r.LicenseNumber);
Console.WriteLine("{0}", r.Address);
Console.WriteLine("{0}, {1} {2}", r.City, r.State, r.ZIPCode);
}
Console.WriteLine("\n--- eCommerce Businesses ---");
foreach (var e in context.Businesses.OfType<eCommerce>())
{
Console.WriteLine("{0} (#{1})", e.Name, e.LicenseNumber);
Console.WriteLine("Online address is: {0}", e.URL);
}
}
The code in Listing 2-19 creates and initializes instances of the Business entity type and the two derived types.
To add these to the Database Context, we use the Add() method exposed on the Business entity set in the context.
On the query side, to access all of the businesses, we iterate through the Businesses entity set. For the derived
types, we use the OfType<>() method specifying the derived type to filter the Business entity set.
 
Search WWH ::




Custom Search