Entity Framework 6 Recipes 2nd Edition(13-1)译 -> 优化TPT继承模型的查询

问题

你想提高在一个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必须把基类和派生类里表的结果都查询出来,然后检测适应的类型来实例化实体,依据你模型的派生类的数量和复杂度,可能产生更多的额外工作.当然,优化的前提是你要确切地知道查询所要返回的具体类型.

转载于:https://www.cnblogs.com/kid1412/p/5492928.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值