Database Reference
In-Depth Information
Following is the output of the code in Listing 2-25:
--- All Employees ---
Jane Doe (Full Time)
John Smith (Full Time)
Tom Jones (Hourly)
--- Full Time ---
Jane Doe
John Smith
--- Hourly ---
Tom Jones
The code in Listing 2-25 creates, initializes, and adds two full-time employees and an hourly employee. On the
query side, we retrieve all of the employees and use the is operator to determine what type of employee we have.
We indicate the employee type when we print out the employee's name.
In separate code blocks, we retrieve the full-time employees and the hourly employees using the OfType<>()
method.
Best Practice
There is some debate over when to use abstract base entities in TPH inheritance and when to create a condition
on the base entity. The difficulty with a concrete base entity is that it can be very cumbersome to query for all of the
instances in the hierarchy. The best practice is that if your application never needs instances of the base entity is to
make it abstract.
If your application needs instances of the base entity, consider introducing a new derived entity to cover the
condition for the concrete base entity. For example, we might create a new derived class, such as UnclassifiedEmployee.
Once we have this new derived entity, we can safely make our base entity abstract. This provides us with a simple way to
query for condition formally covered by the base entity with a condition.
There are some rules to keep in mind when using TPH. First, the conditions used must be mutually exclusive.
That is, you cannot have a row that can conditionally map to two or more types.
Second, the conditions used must account for every row in the table. You cannot have a row in the table that
has a discriminator value that does not map the row to exactly one type. This rule can be particularly troubling if you
are working with a legacy database in which other applications are creating rows for which you have no appropriate
condition mappings. What will happen in these cases? The rows that do not map to your base or derived types will
simply not be accessible in your model.
The discriminator column cannot be mapped to an entity property unless it is used in an is not null condition
At first, this last rule might seem overly restrictive. You might ask, “How can I insert a row representing a derived
type if I can't set the discriminator value?” The answer is rather elegant. You simply create an instance of the derived
type and add it to the context in the same way that you would any other entity instance. Object Services takes care of
creating the appropriate insert statements to create a row with the correct discriminator value.
 
Search WWH ::




Custom Search