Database Reference
In-Depth Information
How It Works
There are two different ways to model our invoices and deleted invoices. The approach we've shown here is
only recommended if you have an existing model and code base, and you would like to add the DeletedInvoice
derived type with as little impact as possible to the existing code. For a new model, it would be better to derive an
ActiveInvoice type and a DeletedInvoice type from the Invoice base type. In this approach, you would mark the base
type as abstract.
Using the approach we've shown here, you could can determine, as we do in the code in Listing 6-37, if the entity
is a DeletedInvoice, either by casting or by using the OfType<>() method. However, you can't select for the Invoice
entity alone. This is the critical drawback to the approach we've shown here.
The approach you should use for new code is to derive two new entities: ActiveInvoice and DeleteInvoice. With
these two sibling types, you can use either casting or the OfType<>() method to operate on either type uniformly.
Listing 6-37. Using the as Operator to Determine If We Have an Invoice or DeletedInvoice
using (var context = new EF6RecipesContext())
{
context.Invoices.Add(new Invoice { Amount = 19.95M,
Description = "Oil Change",
Date = DateTime.Parse("4/11/13") });
context.Invoices.Add(new Invoice { Amount = 129.95M,
Description = "Wheel Alignment",
Date = DateTime.Parse("4/01/13") });
context.Invoices.Add(new DeletedInvoice { Amount = 39.95M,
Description = "Engine Diagnosis",
Date = DateTime.Parse("4/01/13") });
context.SaveChanges();
}
using (var context = new EF6RecipesContext())
{
foreach (var invoice in context.Invoices)
{
var isDeleted = invoice as DeletedInvoice;
Console.WriteLine("{0} Invoice",
isDeleted == null ? "Active" : "Deleted");
Console.WriteLine("Description: {0}", invoice.Description);
Console.WriteLine("Amount: {0}", invoice.Amount.ToString("C"));
Console.WriteLine("Date: {0}", invoice.Date.ToShortDateString());
Console.WriteLine();
}
}
 
Search WWH ::




Custom Search