Database Reference
In-Depth Information
You want to query this model for a given employee. To improve the performance of the query when you know
the type of employee, use the OfType<T>() operator to narrow the result to entities of the specific type, as shown
in Listing 13-1.
Listing 13-1. Improving the Performance of a Query Against a Table per Type Inheritance Model When You Know
the Entity Type
using (var context = new EFRecipesEntities())
{
context.Employees.Add(new SalariedEmployee { Name = "Robin Rosen",
Salary = 89900M });
context.Employees.Add(new HourlyEmployee { Name = "Steven Fuller",
Rate = 11.50M });
context.Employees.Add(new HourlyEmployee { Name = "Karen Steele",
Rate = 12.95m });
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
// a typical way to get Steven Fuller's entity
var emp1 = context.Employees.Single(e => e.Name == "Steven Fuller");
Console.WriteLine("{0}'s rate is: {1} per hour", emp1.Name,
((HourlyEmployee)emp1).Rate.ToString("C"));
// slightly more efficient way if we know that Steven is an HourlyEmployee
var emp2 = context.Employees.OfType<HourlyEmployee>()
.Single(e => e.Name == "Steven Fuller");
Console.WriteLine("{0}'s rate is: {1} per hour", emp2.Name,
emp2.Rate.ToString("C"));
}
Following is the output of the code in Listing 13-1:
Steven Fuller's rate is: $11.50 per hour
Steven Fuller's rate is: $11.50 per hour
How It Works
The key to making the query in a Table per Type inheritance model more efficient is to tell Entity Framework
explicitly the type of the expected result. This allows Entity Framework to generate code that limits the search to
the specific tables that hold the values for the base type and the derived type. Without this information, Entity
Framework has to generate a query that pulls together all of the results from all of the tables holding derived type
values, and then it determines the appropriate type for materialization (for example, fetching and transformation
of data to entity objects). Depending on the number of derived types and the complexity of your model, this may
require substantially more work than is necessary. Of course, this assumes that you know exactly what derived type
the query will return.
 
Search WWH ::




Custom Search