实体框架在每次编译后首次加载都很慢 [英] Entity framework very slow to load for first time after every compilation
问题描述
测试是在Visual Studio 2012中使用实体框架6完成的,我也使用T4视图模板预编译视图。数据库位于SQL Server 2008上。我们有大约400个POCO(400个映射文件),数据库表中只有100行数据。
以下捕获是我的测试代码和结果。
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);
}
测试结果
首次15480毫秒
第二次10毫秒
在第一个查询EF中编译模型。这可能需要一些严重的时间,一个这样大的模型。
总结:
- 使用缓存的数据库模型存储
- 生成预编译视图
- 使用n-gen生成实体框架的预编译版本,以避免错误
我还会确保在执行基准测试时在发布模式下编译应用程序。
另一个解决方案是分析DBContext。 400个实体是很多的,应该比较好的使用较小的块。我没有尝试过,但我认为可以逐个构建模型,这意味着没有一个负载需要15秒。参见Julie Lerman的这篇文章 https://msdn.microsoft.com/en-us /magazine/jj883952.aspx
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.
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");
}
Test results
First Time 15480 milliseconds
Second Time 10 milliseconds
On the first query EF compiles the model. This can take some serious time for a model this large.
Here is 3 suggestions: http://www.fusonic.net/en/blog/2014/07/09/three-steps-for-fast-entityframework-6.1-first-query-performance/
A summary:
- Using a cached db model store
- Generate pre-compiled views
- Generate pre-compiled version of entityframework using n-gen to avoid jitting
I would also make sure that I compile the application in release mode when doing the benchmarks.
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屋!