Search code examples
c#entity-framework-coreblazorblazor-webassembly

EFCore in hosted Blazor WASM


I'm trying to use EFCore within a hosted Blazor WASM Application.

My Startup.cs contains the following Snippet:

        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();
        }

In my PostgresContext I tried to do the follwoing:

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

This is not working, and the database does not get created. However; When I use EnsureCreated()/EnsureDeleted() inside a Controller it works fine. Although this is a solution I am not happy with, since those Functions should not be called from a Controller in my opinion.

        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();
}

What would be the correct way to initialize the Database (while in Development)?


Solution

  • The best practice for production is to not create or migrate the database at runtime. Instead doing that at deployment-time. To do it at runtime, either run EnsureCreated() / Migrate at startup or create a controller that only manages the creation of your database and call that after deployment.