实体框架在每次编译后第一次加载非常慢 [英] Entity framework very slow to load for first time after every compilation

查看:34
本文介绍了实体框架在每次编译后第一次加载非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我在使用实体框架对 SQL Server 数据库进行第一次查询时遇到问题.我试图寻找答案,但似乎没有人真正有解决方案.

As the title suggest i'm having a problem with the first query against a SQL Server database using the Entity Framework. I have tried looking for an answer but no one seems to actually have a solution to this.

测试是在 Visual Studio 2012 中使用 Entity Framework 6 完成的,我还使用了 T4 视图模板来预编译视图.数据库在 SQL Server 2008 上.我们有大约 400 个 POCO(400 个映射文件),数据库表中只有 100 行数据.

The tests was done in Visual Studio 2012 using Entity Framework 6, I also used the T4 views template to pre-compile the views. The database was on a SQL Server 2008. We have about 400 POCOs (400 mapping files), only have 100 rows data in database table.

以下是我的测试代码和结果.

Following capture is my test code and result.

static void Main(string[] args){
    Stopwatch st=new Stopwatch();
    st.Start();
    new TestDbContext().Set<Table1>.FirstOrDefault();
    st.stop();
    Console.WriteLine("First Time "+st.ElapsedMilliseconds+ " milliseconds");

    st.Reset();
    st.Start();
    new TestDbContext().Set<Table1>.FirstOrDefault();
    st.stop();
    Console.WriteLine("Second Time "+st.ElapsedMilliseconds+ " milliseconds");
}

测试结果

First Time 15480 milliseconds
Second Time 10 milliseconds

推荐答案

在第一次查询时,EF 编译模型.对于这么大的模型,这可能需要一些认真的时间.

On the first query EF compiles the model. This can take some serious time for a model this large.

这里有 3 个建议:http://www.fusonic.net/en/blog/2014/07/09/three-steps-for-fast-entityframework-6.1-first-query-performance/

总结:

  1. 使用缓存的数据库模型存储
  2. 生成预编译视图
  3. 使用 n-gen 生成实体框架的预编译版本以避免抖动

我还会确保在执行基准测试时以发布模式编译应用程序.

I would also make sure that I compile the application in release mode when doing the benchmarks.

另一个解决方案是查看拆分 DBContext.400 个实体很多,使用较小的块应该会更好.我还没有尝试过,但我认为可以一个一个地构建模型,这意味着没有一个负载需要 15 秒.请参阅 Julie Lerman 的这篇文章 https://msdn.microsoft.com/en-us/杂志/jj883952.aspx

Another solution is to look at splitting the DBContext. 400 entities is a lot and it should be nicer to work with smaller chunks. I haven't tried it but I assume it would be possible to build the models one by one meaning no single load takes 15s. See this post by Julie Lerman https://msdn.microsoft.com/en-us/magazine/jj883952.aspx

这篇关于实体框架在每次编译后第一次加载非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆