由于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>()); } } }
如果是WCF服务寄宿在IIS中的项目,则需要在Web宿主种增加Global.asax配置文件,并在Application_Start方法中加入上述优化代码即可
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毫秒
时间: 2024-10-13 11:09:31