Jac*_*kal 1 c# entity-framework-core
我有大约 40 个实体,每次编译并运行我的应用程序后,第一次调用 DbContext 都会花费近 10 秒的时间。有没有办法让它运行得更快?
\n\n这是当用户已经登录我的应用程序时我在第一次通话时所做的事情
\n\n页面模型
\n\npublic class CreateModel : PageModel\n{\n private readonly IToastNotification _toastNotification;\n private readonly ICelulaService _celulaService;\n\n public CreateModel(IToastNotification toastNotification, ICelulaService celulaService)\n {\n _toastNotification = toastNotification;\n _celulaService = celulaService;\n }\n\n public IList<Celula> Celulas { get; set; }\n\n public void OnGet()\n {\n Celulas = _celulaService.GetAutomated();\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n服务与接口
\n\npublic interface ICelulaService\n{\n IList<Celula> GetAutomated();\n}\n\npublic IList<Celula> GetAutomated()\n{\n return _context.Celulas\n .Where(c => c.Automated)\n .ToList();\n}\nRun Code Online (Sandbox Code Playgroud)\n\n该模型
\n\n[Table("hCelulas")]\npublic class Celula\n{\n public int Id { get; set; }\n [Required]\n [MaxLength(10)]\n [Display(Name = "C\xc3\xa9lula")]\n public string Nome { get; set; }\n\n\n public bool Automated { get; set; }\n\n public int? CheckListId { get; set; }\n public CheckList CheckList { get; set; }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n数据库上下文
\n\npublic class DatabaseContext : DbContext\n{\n public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)\n {\n\n }\n\n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n {\n\n }\n\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n { \n modelBuilder.Entity<Celula>()\n .HasIndex(x => x.Nome)\n .HasName("IX_Nome_Index")\n .IsUnique();\n\n modelBuilder.Entity<Celula>().HasData(\n new Celula { Id = 1, Nome = "3.9.X", Automated = true, },\n new Celula { Id = 2, Nome = "3.9.Y", Automated = true, },\n new Celula { Id = 3, Nome = "3.9.Z", Automated = true, }\n );\n\n }\n public DbSet<Celula> Celulas { get; set; } \n}\nRun Code Online (Sandbox Code Playgroud)\n\n并在启动时
\n\nservices.AddDbContext<DatabaseContext>(options =>\n{ options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions =>\n {\n sqlOptions.EnableRetryOnFailure(\n maxRetryCount: 2,\n maxRetryDelay: TimeSpan.FromSeconds(1),\n errorNumbersToAdd: null);\n });\n });\nRun Code Online (Sandbox Code Playgroud)\n\n连接字符串
\n\n\n\n\n"DefaultConnection": "服务器=(localdb)\\mssqllocaldb;数据库=DatabaseTest;Trusted_Connection=True;",
\n
更新
\n\n添加了一些数据,这基本上是我遇到缓慢时的数据。
\n在 EF-core 6.0 中添加了一个新功能,允许使用编译模型.
编译后的模型可以通过点命令生成:
dotnet ef dbcontext optimize
Run Code Online (Sandbox Code Playgroud)
...之后它可以在代码中使用:
dotnet ef dbcontext optimize
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4145 次 |
| 最近记录: |