【发布时间】:2019-12-04 14:45:10
【问题描述】:
我有大约 40 个实体,每次编译并运行我的应用程序后,第一次调用 DbContext 都需要将近 10 秒。有没有办法让它运行得更快?
当用户已经登录我的应用程序时,这是我在第一次通话时所做的
页面模型
public class CreateModel : PageModel
{
private readonly IToastNotification _toastNotification;
private readonly ICelulaService _celulaService;
public CreateModel(IToastNotification toastNotification, ICelulaService celulaService)
{
_toastNotification = toastNotification;
_celulaService = celulaService;
}
public IList<Celula> Celulas { get; set; }
public void OnGet()
{
Celulas = _celulaService.GetAutomated();
}
}
服务和接口
public interface ICelulaService
{
IList<Celula> GetAutomated();
}
public IList<Celula> GetAutomated()
{
return _context.Celulas
.Where(c => c.Automated)
.ToList();
}
模型
[Table("hCelulas")]
public class Celula
{
public int Id { get; set; }
[Required]
[MaxLength(10)]
[Display(Name = "Célula")]
public string Nome { get; set; }
public bool Automated { get; set; }
public int? CheckListId { get; set; }
public CheckList CheckList { get; set; }
}
数据库上下文
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Celula>()
.HasIndex(x => x.Nome)
.HasName("IX_Nome_Index")
.IsUnique();
modelBuilder.Entity<Celula>().HasData(
new Celula { Id = 1, Nome = "3.9.X", Automated = true, },
new Celula { Id = 2, Nome = "3.9.Y", Automated = true, },
new Celula { Id = 3, Nome = "3.9.Z", Automated = true, }
);
}
public DbSet<Celula> Celulas { get; set; }
}
在启动时
services.AddDbContext<DatabaseContext>(options =>
{ options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 2,
maxRetryDelay: TimeSpan.FromSeconds(1),
errorNumbersToAdd: null);
});
});
连接字符串
"DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=DatabaseTest;Trusted_Connection=True;",
更新
添加了一些数据,这基本上是我遇到缓慢时的数据。
【问题讨论】:
-
第一次调用你做了什么样的CRUD操作?请向我们展示最小可复制样品。
-
可能是 stackoverflow.com/questions/49353909/ef-core-2-1-slow-startup 、 stackoverflow.com/questions/52423965/… 、 stackoverflow.com/questions/30423838/… 或 stackoverflow.com/questions/46683370/… 的骗子。当您在调试器之外以
release模式运行时会发生什么? -
在 10-12 秒中稍微快了 4-5 秒。我误解了这个问题。这是在生产中。在本地,发布时花了 10s+,没有调试