问题
你想提高在一个TPT继承模型里的查询
解决方案
让我们假设有一个简单的TPT继承模型,如图Figure 13-1
Figure 13-1. A simple Table per Type inheritance model for Salaried and Hourly employees
你想从这个模型里查询一个指定的employee.为了提高查询性能,当你知道这个employee的具体类型时,就用OfType<T>()操作符来指定结果的实体的类型,如代码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())
{
// 一个典型的查询实体的方式
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"));
// 如果知道实体的类型为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"));
}
输出结果如下:
Steven Fuller's rate is: $11.50 per hour
Steven Fuller's rate is: $11.50 per hour
它是如何工作的
关键是在TPT继承模型里告诉EF查询所期望的目标实体的具体类型,这样EF就能为基类或派生类查询对应的表.如果没有告诉EF查询所期望的类型信息,EF必须把基类和派生类里表的结果都查询出来,然后检测适应的类型来实例化实体,依据你模型的派生类的数量和复杂度,可能产生更多的额外工作.当然,优化的前提是你要确切地知道查询所要返回的具体类型.