标签:
由于EF Code First模式没有模型文件,所以很多一次请求的时候速度比较慢,EF需要将对应的数据库映射关系加载到内存里面,往后请求就比较快。可以通过在程序初始化的时候增加一段代码来优化EF第一次执行的速度,具体代码如下
//EF暖机操作 using (CompanyContext dbContext = new CompanyContext()) { var objectContext =((IObjectContextAdapter)dbContext).ObjectContext; var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappingCollection.GenerateViews(new List<EdmSchemaError>()); }
控制台项目则把上面一段代码放在Main方法中即可,在需要调用的方法之前执行。
static void Main(string[] args) { //EF暖机操作 using (CompanyContext dbContext = new CompanyContext()) { var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappingCollection.GenerateViews(new List<EdmSchemaError>()); } Stopwatch sw = new Stopwatch(); sw.Start(); using (DbContext dbContext = new CompanyContext()) { foreach (var entity in dbContext.Set<UserInfo>()) { Console.WriteLine(entity.UserName); } } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); Console.ReadKey(); }
如果是Asp.Net WebForm或者MVC项目则把上述代码加载Application_Start方法中即可,即在网站启动时候就进行映射关系的加载
WebForm项目
protected void Application_Start(object sender, EventArgs e) { //EF暖机代码 using (CompanyContext dbContext = new CompanyContext()) { var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappingCollection.GenerateViews(new List<EdmSchemaError>()); } }
MVC项目
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //EF优化代码 using (CompanyContext dbContext = new CompanyContext()) { var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; var mappintCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappintCollection.GenerateViews(new List<EdmSchemaError>()); } } }
protected void Application_Start(object sender, EventArgs e) { //EF暖机操作 using (CompanyContext dbContext = new CompanyContext()) { var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext; var mappintCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace); mappintCollection.GenerateViews(new List<EdmSchemaError>()); } }
对比效果如下
优化前的效果,耗时3281毫秒
优化后的效果,耗时130毫秒
标签:
原文地址:http://www.cnblogs.com/enternal/p/4764741.html