【问题标题】:EFCore in hosted Blazor WASM托管 Blazor WASM 中的 EFCore
【发布时间】:2021-10-07 15:58:47
【问题描述】:

我正在尝试在托管的 Blazor WASM 应用程序中使用 EFCore。

我的Startup.cs 包含以下代码段:

        public void ConfigureServices(IServiceCollection services)
        {
            var databaseConfig = Configuration.GetSection("DATABASE").Get<DatabaseOptions>();
            var connectionString = databaseConfig.DbConnectionString;
            // services.AddDbContextFactory<PostgresContext>(opt => opt.UseNpgsql(connectionString));
            services.AddDbContext<PostgresContext>(opt => opt.UseNpgsql(connectionString));

            services.AddControllersWithViews();
            services.AddRazorPages();
        }

在我的PostgresContext 中,我尝试执行以下操作:

        public PostgresContext(DbContextOptions<PostgresContext> options) : base(options)
        {
            // Database.EnsureDeleted();
            // Database.EnsureCreated();
        }

这不起作用,并且没有创建数据库。 然而;当我在控制器中使用EnsureCreated()/EnsureDeleted() 时,它工作正常。虽然这是一个我不满意的解决方案,但在我看来,不应从控制器调用这些函数。

        private readonly IWebHostEnvironment _env;
        private readonly PostgresContext _context;

        public MobileController(PostgresContext context, IWebHostEnvironment env)
        {
            _context = context;
            _env = env;
        }

....

public async Task SomeFunction {
            await _context.Database.EnsureDeletedAsync();
            await _context.Database.EnsureCreatedAsync();
            
            await _context.AddRangeAsync(cranes);
            await _context.SaveChangesAsync();
}

初始化数据库的正确方法是什么(在开发阶段)?

【问题讨论】:

  • “这不起作用,并且数据库没有被创建” - 是否有 任何 数据库活动?记录了什么? PostgreSQL 的log_statement 说正在发生什么?

标签: c# entity-framework-core blazor blazor-webassembly


【解决方案1】:

生产的最佳实践是在运行时创建或迁移数据库。而是在部署时这样做。要在运行时执行此操作,请在启动时运行 EnsureCreated() / Migrate,或者创建一个仅管理数据库创建并在部署后调用它的控制器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2020-08-17
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多