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

  • 相关阅读:
    06 is和==的区别 encode()编码 decode()解码
    05 dic的增删改查 字典的嵌套 考试题dic.get()的相关使用
    03 编码 int ,bool,str的常用操作 主要讲str
    01 基本数据类型 变量 if语句
    04 列表的增删改查 常用方法 元祖 range
    02 while循环 格式化输出 运算符
    多校2 Harmonious Army hdu6598 网络流
    P3159 [CQOI2012]交换棋子 网络流
    P2172 [国家集训队]部落战争 最大流
    P2402 奶牛隐藏 网络流
  • 原文地址:https://www.cnblogs.com/kid1412/p/5492928.html
Copyright © 2011-2022 走看看