在下面的代码片段中,首先加载的List I比其他代码片段多出约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)); }
答案 0 :(得分:1)
应用程序中的第一个查询(或SaveChanges
调用)会导致EF初始化。有一些选项可以提高此步骤的性能(例如预编译“视图”),但它总是会慢得多。
答案 1 :(得分:0)
正如Ladislav所说,由于EF初始化,第一个查询速度较慢。 也就是说,您可以通过在应用程序启动时调用以下代码来强制EF在应用程序启动时进行初始化。
using (var db = new MyDataEntities()) {
context.Database.Initialize(force: true);
}
只需要 时,您希望它发生在应用程序的开头或它发出的第一个Query / SaveChanges中。