OnModelCreating方法官方说应用程序第一次执行时才会执行一次这个方法。理解起来这样设计确实很好。一次性把表都加载到内存,后续操作直接从内存中读取;
实际情况:项目数据库有1000多张表,执行OnModelCreating非常耗时,执行完OnModelCreating方法1分钟以上。仅仅只是第一次加载耗时1分种以上勉强可以接受,毕竟第一次访问的人时程序员自己。后面客户访问速度就快。
问题:程序发布到IIS上,第一次访问程序慢一点,后续客户访问速度很快。但是时间久了(目前测试半个小时左右)没有访问程序,再次访问的时候。程序又去执行OnModelCreating 导致程序访问时间又要消耗1分钟以上。给人的体验非常差。
怀疑是应用程序池被回收,导致访问又执行OnModelCreating 方法。
请问有什么方法可以解决这个问题吗?
#region 重载
/// <summary>
/// 模型创建重载
/// </summary>
/// <param name="modelBuilder">模型创建器</param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Log log = LogFactory.GetLogger("");
log.Debug(DateTime.Now.ToString() + "程序启动第一次执行");
System.Data.Entity.Database.SetInitializer<DatabaseContext>(null);
int i = 1;
string assembleFileName = Assembly.GetExecutingAssembly().CodeBase.Replace("QY.DataBase.SqlServer.DLL", "QY.Application.Mapping.DLL").Replace("file:///", "");
Assembly asm = Assembly.LoadFile(assembleFileName);
var typesToRegister = asm.GetTypes()
.Where(type => !String.IsNullOrEmpty(type.Namespace))
.Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));
foreach (var type in typesToRegister)
{
i++;
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.Configurations.Add(configurationInstance);
}
base.OnModelCreating(modelBuilder);
}
#endregion