【问题标题】:What is the bottle neck in using a DBContext?使用 DBContext 的瓶颈是什么?
【发布时间】:2013-12-27 21:30:54
【问题描述】:

在下面的代码 sn-p 中,我首先加载的 List 比其他代码多花费大约 3000 毫秒。 这使我认为在第一个 .ToList() 上发生了某些事情,而在以后的 .ToList() 调用中没有发生。会是什么呢?

我希望有一些可以提高性能的方法。

db 是我的 DBContext 实例。

使用 (var db = new MyDataEntities())

{

            const int linkTypeId = 3;

            var sw = new Stopwatch();
            sw.Start();


            // section A
            sw.Restart();
            var qry2 = from p in db.ViewPropertyPairs where p.LinkID == JobId && p.LinkType == linkTypeId select p;
            this.ViewPropertyPairs = qry2.ToList();
            sw.Stop();
            Debug.Print(string.Format("{0}  ms for to view property pair list", sw.ElapsedMilliseconds));

            // Section B

            sw.Restart();
            this.PropertyNames = db.PropertyNames.ToList();
            sw.Stop();
            Debug.Print(string.Format("{0}  ms for propertynames",  sw.ElapsedMilliseconds));


            // Section C
            sw.Restart();
            var qry =from p in db.PropertyPairs where p.LinkID == JobId && p.LinkType == linkTypeId select p ;
            this.PropertyPairs = qry.ToList();
            sw.Stop();
            Debug.Print(string.Format("{0}  ms for to property pair list", sw.ElapsedMilliseconds));


        }

【问题讨论】:

  • 这是您的应用程序对数据库执行的第一个查询吗?在这种情况下,它是 EF 基础设施的初始化。
  • 就是这样。谢谢你。你能把它添加为答案吗?

标签: performance entity-framework-6


【解决方案1】:

应用程序中的第一个查询(或SaveChanges 调用)会导致 EF 初始化。有一些选项可以提高此步骤的性能(例如预编译“视图”),但它总是会明显变慢。

【讨论】:

    【解决方案2】:

    正如 Ladislav 所说,由于 EF 初始化,第一个查询速度较慢。 也就是说,您可以通过在应用程序启动时调用以下代码来强制 EF 在应用程序启动时进行初始化。

    using (var db = new MyDataEntities()) {
        context.Database.Initialize(force: true);
    }
    

    只是何时您希望它发生的问题,在您的应用程序开始时或在它进行的第一次查询/保存更改期间。

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2020-03-17
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      相关资源
      最近更新 更多