【发布时间】: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