【问题标题】:Entity Framework Core too slow on First call实体框架核心在第一次调用时太慢了
【发布时间】: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;",

更新

添加了一些数据,这基本上是我遇到缓慢时的数据。

【问题讨论】:

标签: c# entity-framework-core


【解决方案1】:

有一个issue on EF's backlog requesting compiled models。使用编译模型存储是减少冷启动时间的一种方法。但不幸的是,正如许多其他功能请求一样,EF 团队尚未给予高度优先级。

要让它更接近待办事项的顶部,你唯一能做的就是投票给它。像许多人一样添加紧迫的 cmets 并没有帮助。他们只会浪费团队的时间。这是一个令人惊讶的小团队。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2019-02-27
    • 2019-02-19
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多